The C Strcmp function is one of the String Function, which is used to compare two strings and check whether those two strings (group of characters) are equal or not?.
In this article, we will show you, How to use strcmp in C Programming language with example. The C strcmp method will perform string comparison based on the given strings and returns any of the following three values:
- This will return -1, if str1 is less than the data inside str2
- This will return +1, if str1 is greater than data inside the str2
- and, this 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 comparison.
- str2: This argument is required. Please specify the valid string to perform comparison. This argument will compare against the str1
TIP: You have to include the #include<string.h> header before using this C strcmp string function.
C strcmp function Example
The strcmp function is used to compare two strings (character array) and returns the integer output. This C 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); }
OUTPUT
ANALYSIS
Within this C strcmp function example, First, we declared three character arrays str1, str2, str3, and we assigned some random string data (group of characters).
char str1[50] = "abc"; char str2[50] = "def"; char str3[] = "ghi";
Following statement is using strcmp function to compare the character array in str1 with str2, and returns the integer value. We are assigning the return value to previously declared i variable. As we all know, ‘abc’ will come before the ‘def’, that’s why strcmp method is returning -1 (Negative one)
i = strcmp(str1, str2);
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 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");
Thank You for Visiting Our Blog