C strcmp()

The strcmp() function is defined in the string.h header file. It helps to compare the two given strings character by character. The strings are equal the function will return a value of zero.


int strcmp(const char *str1, const char *str2); #where str1,str2 are strings

 

strcmp() Parameters: 

The strcmp() function takes two parameters. The string comparison will continue until it reaches the end of the string or the characters are not the same.

Parameter Description Required / Optional
str1  the first string to be compared Required
str2 the second string to be compared Required

strcmp() Return Value

The function returns a value of zero if the strings are equal otherwise it returns a non-zero value.

Input Return Value
str1 < str2 value < 0
str2 < str1 value > 0
str1 = str2 value = 0

Examples of strcmp() 

Example 1: Working of strcmp() function in C?


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

int main()
{
   char string1[20];
   char string2[20];
   int out;


   strcpy(string1, "flowers");
   strcpy(string2, "FLOWERS");

   out = strcmp(string1, string2);

   if(out < 0) {
      printf("string1 is less than string2");
   } else if(ret > 0) {
      printf("string2 is less than string1");
   } else {
      printf("string1 is equal to string2");
   }
   
   return(0);
}

Output:


string2 is less than string1

Example 2: How strcmp() works in C?


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

int main (){

  char string1[] = "abcd", string2[] = "abCd", string3[] = "abcd";
  int out;

  // comparing string1 and string2
  out = strcmp(string1, string2);
  printf("strcmp(string1, string2) = %d\n", out);

  // comparing string1 and string3
  out = strcmp(string1, string3);
  printf("strcmp(string1, string3) = %d\n", out);

  return 0;
}

Output:


strcmp(string1, string2) = 1
strcmp(string1, string3) = 0