C programming strcmp string.h


In C programming the <string.h> strcmp function compare two strings for equality in their characters.The declaration of the function is given below.

int strcmp(const char *s1, const char *s2);

Parameters:
s1 -The first string.

s2 -The second string that is to be compared with the first string.

Return type
int -Returns 0 if the two strings are equal.Returns 1 if ‘s1’ is greater than s2.Returns value less than zero(most probably -1) if s1 is smaller than s2.

The function compares the two string by comparing one character at a time.When it come across a character greater or smaller than the other the character of the other string,the string with that greater or smaller unsigned character value is the greater or smaller string.

Code example

char s1[] = “New string”,
s2[] = “New string”,
s3[] = “New String” ,
s4[]=”new string” ,
s5[]=”New”;

int ret;

//s1==s2
ret =strcmp(s1, s2);

printf(“ret=%d”, ret);

//s1>s3
ret =strcmp(s1, s3);

printf(“\nret=%d”, ret);

//s1<s4
ret =strcmp(s1, s4);

printf(“\nret=%d”, ret);

//s1>s5
ret =strcmp(s1, s5);

printf(“\nret=%d”, ret);

Output,

ret=0
ret=1
ret=-1
ret=1


Related links

->C strcoll string.h

->C strxfrm string.h

->C memcmp string.h

->C strncmp string.h