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.
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);
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:
If Str1
is equal to Str2
, it returns a :
If Str1
is less than Str2
, it returns a (negative value):
If Str1
is greater than Str2
, it returns a (positive value):
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;}