Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

strcmp
comparison
string
c language

How to compare strings using strcmp() function in C

Educative Answers Team

The strcmp() function is a built-in library function declared in the string.h header file. It compares two strings and returns an integer after comparison.

Syntax

strcmp() takes two strings as arguments and returns an integer. Strings are case sensitive, i.e., abc is not equal to Abc.

int strcmp (char * Str1, char * Str2);

Cases

Every character holds an ASCII value (an integer ranging from 0 to 127), for example, A holds the ASCII value of 65 and a holds the ASCII value of 97. So, in the comparison between two strings, their ASCII values are compared. Let’s look at the possible cases:

Case 1

If Str1 is equal to Str2, it returns a 00:

1 of 5

Case 2

If Str1 is less than Str2, it returns a 32-32 (negative value):

1 of 3

Case 3

If Str1 is greater than Str2, it returns a 3232 (positive value):

1 of 3

Let’s look at an example of strcmp():

#include<stdio.h>
#include<string.h>

int main() {
  char str1[] = "abcd", str2[] = "abcd";
  int a = strcmp(str1, str2);
  printf("Case 1: %d\n\n", a);
  
  char Str1[] = "abCd", Str2[] = "abcd";
  a = strcmp(Str1, Str2);
  printf("Case 2: %d\n\n", a);
  
  char STR1[] = "abcd", STR2[] = "abCd";
  a = strcmp(STR1, STR2);
  printf("Case 3: %d\n\n", a);
  return 0;
}

RELATED TAGS

strcmp
comparison
string
c language
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring