C String Functions - C strcmp






int strcmp(const char *str1 , const char *str2 );

Compares the string str1 to the string str2.

Returns zero if str1 and str2 are equal.

Returns less than zero or greater than zero if str1 is less than or greater than str2 respectively.

Prototype

int strcmp ( const char * str1, const char * str2 );

Parameter

This function has the following parameter.

str1
C string to be compared.
str2
C string to be compared.

Return

Returns an integral value indicating the relationship between the strings.

  • <0 indicates the first character that does not match has a lower value in ptr1 than in ptr2
  • 0 indicates the contents of both strings are equal
  • >0 indicates the first character that does not match has a greater value in ptr1 than in ptr2




Example


#include <stdio.h>
#include <string.h>
/* www .  jav  a 2  s.co m*/
int main (){
  char key[] = "apple";
  char buffer[80];
  do {
     printf ("Guess my favorite fruit? ");
     fflush (stdout);
     scanf ("%79s",buffer);
  } while (strcmp (key,buffer) != 0);
  return 0;
} 

       

The code above generates the following result.





Example 2


#include <string.h>
#include <stdio.h>
 /*from  w  ww .ja v a2  s .  c om*/
void demo(const char* lhs, const char* rhs)
{
    int rc = strcmp(lhs, rhs);
    if(rc == 0)
        printf("[%s] equals [%s]\n", lhs, rhs);
    else if(rc < 0)
        printf("[%s] precedes [%s]\n", lhs, rhs);
    else if(rc > 0)
        printf("[%s] follows [%s]\n", lhs, rhs);
 
}
int main(void)
{
    const char* string = "Hello World!";
    demo(string, "Hello!");
    demo(string, "Hello");
    demo(string, "Hello ");
}

The code above generates the following result.