Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

strcmp Function in C: A Practical Guide to Comparing Strings

Basics of Python
Basics of Python
icon
5 Hrs. duration
icon
9 Modules
icon
1800+ Learners
logo
Start Learning

String manipulation is a fundamental skill in any programming language. Many predefined functions in C language can easily manipulate strings. One of the most frequent functions is strcmp(), which compares two strings lexicographically. This article explained how strcmp() works, its usage, and some practical considerations.

What is strcmp()?

The strcmp() function is used to compare two null-terminated strings. It is declared in the <string.h> header file and takes two pointers to the strings as its parameters. The strcmp() function compares the strings character by character based on their ASCII values and returns an integer value, which signifies whether the strings are equal, or if one is greater or less than the other.

Syntax of strcmp in C

The syntax for using strcmp in C is as follows. This function accepts string1 and string2.

 

int strcmp(const char *string1, const char *string2);

Parameters of C strcmp

The strcmp function accepts two parameters, string1 and string2, which are pointers to the characters that must be compared.

Return Value of strcmp in C

The strcmp() function returns an integer value calculated using the first mismatched character between the two strings. There are three possible return values generated by strcmp.

 

  • Zero(0): This integer value returns when both strings are the same, meaning that elements at the same index in both strings are equivalent.

 

The following program demonstrates return value in C language:

 

Program

#include<stdio.h> #include<string.h> int main(){ char string1[]= "Neeraj Kumar" ; char string2[] = "Neeraj Kumar" ; int  rvalue = strcmp(string1, string2) ; if(rvalue == 0){ printf("Strings are equal") ; }else{ printf("String are not equal") ; } printf("n Value returned by strcmp in %d",rvalue) ; return 0 ; }

Output

Strings are equal Value returned by strcmp in 0
  • Greater than zero (>0): If string1 is lexicographically greater than str2. This means that str1 comes after str2 in alphabetical order.

 

The following program demonstrates greater than zero: 

Program

// C program to illustrate strcmp in C #include<stdio.h> #include<string.h> int main() { char string1[] = "Neeraj Kumar"; char string2[] = "Neeraj Kumar"; int rvalue = strcmp(string1, string2); 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 equal Value returned by strcmp is: 0

Program

#include<stdio.h> #include<string.h>  void matchStr(char * string1, char * string2) { int rvalue = strcmp(string1, string2);  if (rvalue == 0) printf("Strings are equal"); else printf("Strings are unequal");  printf("nValue returned by strcmp is: %d", rvalue); }  int main() { char string1[] = "Neeraj Kumar"; char string2[] = "Neeraj Kumar"; matchStr(string1, string2); return 0; }

Output

Strings are equal Value returned by strcmp is: 0

How to use strcmp in C?

In C language, the strcmp function is used to compare two strings. It is declared in the <string.h> header file. This function compares the two strings character by character and determines their relative order.

 

  • If strcmp function returns 0, It means the two strings are equal.
  • If strcmp returns a negative value, the first string is lexicographically less than the second.
  • If strcmp returns a positive value, the first string is lexicographically greater than the second.

 

The following progarm demonstrates the strcmp function:

 

Program

#include<stdio.h> #include<string.h> int main(){ char str1[] = "neeraj" ; char str2[] = "water" ; char str3[] = "computer" ; int result1 = strcmp(str1,str2) ; int result2 = strcmp(str1, str3) ; printf("Comparison of str1 and str2 : %dn", result1) ; printf("Comparison of str2 and str3 %dn",result2) ;  return 0 ; }

Output

Comparison of str1 and str2 : -9 Comparison of str2 and str3 11
DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

More Examples of strcmp in C

Example 1: Comparing Two Equal Strings

The following program demonstrates the strcmp() function in C: #include <stdio.h> #include <string.h> int main(){ char str1[] = "apple" ; char str2[] = "apple" ; int result = strcmp(str1, str2) ; if(result ==0 ){ printf("The strings are equal n") ; }else if(result < 0){ printf("str1 is less than str2. n") ; }else { printf("str1 is greater than str2 n") ; } }

Output

The strings are equal

Example 2: Comparing a String with a Lexicographically Greater String

#include <stdio.h> #include <string.h> int main() { char str1[] = "Neeraj"; char str2[] = "apple"; int result = strcmp(str1, str2); if (result == 0) { printf("The strings are equal.n"); } else if (result < 0) { printf("str1 is less than str2.n"); } else { printf("str1 is greater than str2.n"); }  return 0; }

Output

str1 is less than str2.

Example 3: Comparing a String with a Lexicographically Lesser String

#include <stdio.h> #include <string.h>  int main() { char str1[] = "computer"; char str2[] = "rajkumar";  int result = strcmp(str1, str2);  if (result == 0) { printf("The strings are equal.n"); } else if (result < 0) { printf("str1 is less than str2.n"); } else { printf("str1 is greater than str2.n"); }  return 0; }

Output

str1 is less than str2.

Advantages of strcmp Function in C

There are advantages of the strcmp function in C.

 

  • Standardised Behaviour: Consistent across different C compilers and platforms.
  • Simple to use: This requires only two strings of arguments, making it easy to implement.
  • Direct Comparison: It directly compares strings based on ASCII values.
  • Cross-Language Compatibility: The part of the C standard library facilitating interoperability with other C-based systems and languages.

 

Also Read: goto Statement in C

Disadvantages of strcmp Function in C

Let’s see some disadvantages of the strcmp function in C language:

 

  • Case Sensitivity: The strcmp is case-sensitive, meaning ‘a’ and ‘A’ are considered different characters. This can be a limitation if case-insensitive comparison is needed.
  • Lack of Error Handling: The strcmp does not handle issues like memory corruption or invalid input, so developers must ensure that strings are valid and properly formatted.
  • No Support for Unicode: The strcmp operates on ASCII values and does not effectively handle Unicode characters or multi-byte character sets. Alternative functions or libraries are needed for Unicode.
  • Requires Proper Initialisation: If the strings are not properly initialised or are garbage-initialised, strcmp might behave unpredictably, making proper initialisation and validation crucial.

 

Also Read: String Concatenation in C

Conclusion

The strcmp is a function in the C standard library that compares two strings lexicographically. It takes two null-terminated strings as arguments and returns an integer indicating their relative order. Specifically, it returns 0 if the strings are identical and a negative value if the first string is greater.

 

The comparison is case-sensitive, meaning uppercase and lowercase letters are treated as distinct. To use strcmp effectively, both strings must be properly null-terminated to avoid undefined behaviour. Overall, strcmp is an essential function for string comparison in C, providing a clear method for determining the ordering of strings.

FAQs
The strcmp is used to compare two strings in C. It helps determine if two strings are equal, or if one is greater than or less than the other in lexicographical order.
The strcmp returns 0 when the two strings are identical. This means every character in both strings matches and both strings have the same length.
A negative value indicates that the first string is lexicographically less than the second string.
If both strings are empty, strcmp will return 0, indicating that the strings are equal.
The strcmp does not handle locale-specific comparisons. For locale-aware string comparison, use strcoll, which considers locale settings and collation rules.
brochureimg

The DevOps Playbook

Simplify deployment with Docker containers.

Streamline development with modern practices.

Enhance efficiency with automated workflows.

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.

Data Science

Accelerator Program in Business Analytics & Data Science

Integrated Program in Data Science, AI and ML

Accelerator Program in AI and Machine Learning

Advanced Certification Program in Data Science & Analytics

Technology

Certificate Program in Full Stack Development with Specialization for Web and Mobile

Certificate Program in DevOps and Cloud Engineering

Certificate Program in Application Development

Certificate Program in Cybersecurity Essentials & Risk Assessment

Finance

Integrated Program in Finance and Financial Technologies

Certificate Program in Financial Analysis, Valuation and Risk Management

Management

Certificate Program in Strategic Management and Business Essentials

Executive Program in Product Management

Certificate Program in Product Management

Certificate Program in Technology-enabled Sales

Future Tech

Certificate Program in Gaming & Esports

Certificate Program in Extended Reality (VR+AR)

Professional Diploma in UX Design

Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

© 2024 Hero Vired. All rights reserved