Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is the Strcmp Function in C?
3.
How to Use strcmp in C
4.
Syntax of strcmp() function in C
5.
Parameters of strcmp() function in C
6.
Return value of strcmp() function in C
6.1.
1. Zero ( 0 )
6.2.
C++
6.3.
2.  Greater than Zero ( > 0 )
6.4.
C++
6.5.
3.  Lesser than Zero ( < 0 )
6.6.
C++
7.
Frequently Asked Questions
7.1.
Q. What does the strcmp str1 str2 function return?
7.2.
Q. How to compare two string in C?
7.3.
Q. What does str1 == str2 mean?
7.4.
Q. How to compare 2 strings?
7.5.
Q. What library is strcmp in C?
7.6.
Q. What is the difference between strcmp() and strncmp() functions?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Strcmp() Function in C

Author Manish Kumar
1 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

A library function called strcmp() inside the C programming language compares strings in line in lexicographic order. It compares two string parameters individually with the help of two arguments passed. Characters are repeatedly compared until a null or another individual gets found. It results in 0,1 and -1 values in return.

Strcmp() Function in C: To Compare

Also See Sum of Digits in C and C Static Function

What is the Strcmp Function in C?

The strcmp function in c language is a built-in library function for comparing two strings lexicographically

Okay, before moving on, let's understand what this term 'lexicographically' actually means. Lexicographic comparison is a way in which each character is compared from both strings until a mismatch is found. ASCII (American Standard Code for Information Interchange) codes are used to compare characters.

Most commonly used ASCII codes :

Ascii codes

Let's now see through examples of how the comparison will take place. 😁😁😁😁
 Example 1

String 1: Coding

String 2: Ninjas
 

Example 1

The difference comes from the first character itself. Thus, the second string is larger.

Example 2

String 1: NinJas

String 2: Ninjas

Example 2

We can observe that the difference comes from the fourth character. The ASCII value of the fourth character of the second string is larger, and thus overall second string is larger.
You can also read about the dynamic arrays in c, and  Tribonacci Series

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

How to Use strcmp in C

Here are the steps to use strcmp in C:

  1. Include the Header File: Include the <string.h> header file at the beginning of your program.
  2. Declare Strings: Declare the strings you want to compare using the char data type.
  3. Call strcmp Function: Use the strcmp() function to compare the strings. It takes two arguments: the strings you want to compare.
  4. Check the Return Value: strcmp() returns an integer value:
    • If the return value is 0, the strings are equal.
    • If the return value is less than 0, the first string is lexicographically less than the second string.
    • If the return value is greater than 0, the first string is lexicographically greater than the second string.
  5. Perform Actions Based on Comparison: Based on the return value of strcmp(), you can perform further actions in your program, such as printing a message or executing specific code.

Syntax of strcmp() function in C

The syntax of the strcmp() function in the C programming language is as follows:

Int strcmp(const char *s1, const char *s2);

In this function, we will compare two strings in lexicographical order, and it will return us the answer by comparing the strings s1 and s2.

If ‘s1’ is lexicographically less than ‘s2’, it will return a negative integer value.
If ‘s1’ is lexicographically greater than ‘s2’, it will return a positive integer value.
If ‘s1’ and ‘s2’ are equal, it will return 0.

Parameters of strcmp() function in C

The function called strcmp() in the C programming language takes in two parameters:
'*s1' is a constant pointer that points to the initial string.
In addition, '*s2' is a constant pointer directing to the second string.
Both s1 and s2 are pointers that refer to unmodifiable characters. The function called strcmp() accepts inputs in the form of pointers to character arrays that require comparing.

Return value of strcmp() function in C

In the C programming language, the strcmp() function is a strong tool for comparing strings. It analyzes the characters in two strings and returns an integer value.  In C, the strcmp() method produces an integer value based on the first mismatched character between the two strings. 

The strcmp() function yields three distinct values following the comparison of the two strings, as follows:

1. Zero ( 0 )

If both strings are the same, the return value is zero. That is, elements in both strings with the same index are equivalent.

Example:

  • C++

C++

#include<stdio.h>

#include<string.h>

int main() {
char string1[] = "Ninja";
char string2[] = "Ninja";

// Calling strcmp() and storing the return value
int r = strcmp(string1, string2);

if (r == 0)
printf("Strings are equal");
else
printf("Strings are unequal");
printf("\nValue returned by strcmp() is: %d", r);
return 0;
}

 

Output:

Strings are equal
Value returned by strcmp() is: 0

 

Explanation:

Strings string1 and string2 are declared and initialized in the above code. They are subsequently run using the strcmp() function. The function's return value is saved in the variable r. A conditional statement is used to determine whether or not two strings are the same by determining whether or not the rrva is equal to zero.

2.  Greater than Zero ( > 0 )

If the ASCII value of the first unmatched character in the left-hand side string (string1) is greater than the equivalent character in the right-hand side string (string2), the return value is greater than zero. The difference between the ASCII values of the first unmatched characters in the strings, i.e., (string1-string2), yields the resultant value.

Example:

  • C++

C++

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

int main() {
char string1[] = "scotland";
char string2[] = "india";

int r = strcmp(string1, string2);

// Condition for checking equality
if (r == 0)
printf("Strings are equal");
else
printf("Strings are unequal");

printf("\nValue returned by strcmp() is: %d", r);
return 0;
}

 

Output:

Strings are unequal
Value returned by strcmp() is: 10

 

Description:

Strings string1 and string2 are declared and initialized in the above code. They are subsequently processed by the strcmp() function. The function's return value is saved in the variable r. The first mismatched character in the strings is discovered at index 0, where the characters in both strings are 's' and 'i'. Both characters have ASCII values of 115 and 105, respectively. As a result, the difference in ASCII value equals 10. 

3.  Lesser than Zero ( < 0 )

If the ASCII value of the first unmatched character in the left-hand side string (string1) is less than that of the corresponding character in the right-hand side string (string2), the return value is less than zero. The difference between the ASCII values of the first unmatched characters in the strings, i.e., (string1-string2), yields the resultant value.

Example:

  • C++

C++

#include<stdio.h>

#include<string.h>

int main() {
char string1[] = "Sunday";
char string2[] = "Zombie";

int rvalue = strcmp(string1, string2);

// Condition for checking equality
if (rvalue == 0)
printf("Strings are equal");
else
printf("Strings are unequal");
printf("\nValue returned by strcmp() is: %d", rvalue);
return 0;
}

Output:

Strings are unequal
Value returned by strcmp() is: -7

 

Description:

The first unmatched character in the strings is found at index 0 in the given code, where characters in both strings are S and Z, respectively. Both characters have ASCII values of 83 and 90, respectively. As a result, the difference in ASCII value is -7.

Also see, Short int in C Programming

Frequently Asked Questions

Q. What does the strcmp str1 str2 function return?

The strcmp function's return value is 0 when the two strings are equal. It returns a value less than 0 when str1 compares less than str2 and a value greater than 0 when str1 compares greater than str2. It's important not to make any additional assumptions about the value returned by strcmp.

Q. How to compare two string in C?

We have two strings for comparison. First, we compare the first characters of both strings. If they are equal, the next character gets compared. If not identical, the ASCII value is involved. Their ASCII values ​​get compared in this case. They produce a negative value if the difference is less, a positive value if the difference is more, and zero if both strings are equal.

Q. What does str1 == str2 mean?

When you use the == operator to compare two strings, it will return true if the string variables point to the same java object. Otherwise, it returns false.

Q. How to compare 2 strings?

The strcmp() string library function compares two strings and returns 0 if they are not equal. We can use loops to compare two strings without using the string library function. We can also use pointers or recursion to compare two strings.

Q. What library is strcmp in C?

The C standard string library has a built-in function called strcmp(). This library contains commonly used string manipulation operations. <string.h> header file invokes a call to this library in a program.

Q. What is the difference between strcmp() and strncmp() functions?

The strcmp() function analyzes two strings by identifying either a null character or a difference between the compared characters. On the other hand, the strncmp() function permits constraining the comparison within a specified limit, enhancing search efficiency. 

Conclusion

We extensively discussed the strcmp function in c language. We learned how this function works, its output values and its prototype. The strcmp function in c is very versatile and suitable for comparing strings lexicographically. We also went through a sample code involving the strcmp function in c.

We hope this blog has helped you enhance your knowledge about the topic strcmp function in C. If you like to learn more, you can check out our articles: 

🌐 Static Functions in C

🌐 Operator Precedence in C

🌐 Implicit return type in C

🌐 String Compare in C

🌐 Ternary Operator in C

 

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScript, and many more! If you wish to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! 

If you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blog on the strcmp function in C if you found it helpful and engaging. We hope you enjoyed our blog on the topic: ‘strcmp function in C’.

Happy Learning!

Previous article
strcat() function in c
Next article
Introduction to Structure
Live masterclass