C strcmp Function

The C Strcmp function is one of the String Functions, which is helpful to compare two strings and check whether those two strings (a group of characters) are equal or not?.

The C strcmp method will perform string comparison based on the given strings and returns any of the following three values:

  • It will return -1 if str1 is less than the data inside str2
  • Returns +1, if str1 is greater than data inside the str2
  • and, it will return 0, if str1 and str2 are equal

C strcmp syntax

The basic syntax of the strcmp in C Programming language is as shown below. The following function will accept two character arrays as the parameters. And, it will compare the string data in both the arrays and returns the integer output using the built-in String function strcmp.

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

or we can simply write it as:

int strcmp(str1, str2);
  • str1: This argument is required. Please specify the valid string to perform a comparison.
  • str2: This argument is required. Please specify the valid string to perform the comparison. This argument will compare against the str1

C strcmp function Example

You have to include the #include<string.h> header before using this C strcmp string function. The strcmp function is used to compare two strings (character array) and returns the integer output. This program will help you to understand the strcmp (string compare) with example.

//C strcmp Function example  
#include <stdio.h> 
#include<string.h>

int main()
{
   char str1[50] = "abc";
   char str2[50] = "def";
   char str3[] =  "ghi";
   int i, j, k;
	
   i = strcmp(str1, str2);		
   printf("\n The Comparison of str1 and str2 Strings = %d", i);
 	
   j = strcmp(str3, str2);		
   printf("\n The Comparison of str3 and str2 Strings = %d", j);
   
   k = strcmp(str1, "abc");		
   printf("\n The Comparison of two Strings = %d", k);
}
C strcmp Function 1

Within this C strcmp function example, First, we declared three character arrays str1, str2, str3, and we assigned some random string data (a group of characters).

char str1[50] = "abc";
char str2[50] = "def";
char str3[] =  "ghi";

The following C Programming statement is using an strcmp function to compare the character array in str1 with str2 and returns the integer value. We are assigning the return value to a previously declared i variable. As we all know, ‘abc’ will come before the ‘def’, that’s why the strcmp method is returning -1 (Negative one)

i = strcmp(str1, str2);

The following C strcmp statement will compare the character array (string data) in str2 with str3. As we all know, ‘ghi’ will come after the ‘def’, that’s why the strcmp method is returning 1 (Positive one)

j = strcmp(str3, str2);

Next, we used the string data directly inside the strcmp function. It means, strcmp(“abc”, “abc”)

k = strcmp(str1, "abc");