Home >>c programs >strcmp in C

strcmp in C

strcmp in C

The strcmp C is basically a function in the C language that is generally used to compare the string pointed to by str1 to the string pointed to by str2.

The declaration of the strcmp function in C is extremely easy and is depicted below for your understanding:

Syntax :

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

Here are the parameters of the syntax of the strcmp in C described below:

str1 − This is basically the first string that is to be compared.

str2 − This is basically the second string that is to be compared.

There are certain return values that are returned by this function that are explained below:

  • if the return value < 0 then it will indicate that str1 is less than str2.
  • If the return value > 0 then it will indicate that str2 is less than str1.
  • if the return value = 0 then it will indicate that str1 is equal to str2.

Here is a strcmp in C example depicted below that will make your concept stronger:

#include <stdio.h>
#include <string.h>
int main () 
{
   char str1[10];
   char str2[15];
   int compStr;
   strcpy(str1, "hello");
   strcpy(str2, "hello");

   compStr = strcmp(str1, str2);

   if(compStr < 0) 
   {
      printf("str1 is less than str2");
   } 
   else if(compStr > 0) 
   {
      printf("str2 is less than str1");
   } 
   else 
   {
      printf("Both string is equal");
   }
   return(0);
}
Output :
Both string is equal