C strcmp Function

The C Strcmp function is one of the String Functions, which helps 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 function syntax

The basic syntax of the strcmp in this 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 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 text to perform the comparison. This argument will compare against the str1

C strcmp 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 string comparison) with example.

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

The following Programming statement for i 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 it is returning -1 (Negative one)

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

In the last line, we used the sample text directly inside the strcmp function. It means, (“abc”, “abc”).

#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