strcmp() in C - GeeksforGeeks (2024)

Last Updated : 29 Aug, 2024

Summarize

Comments

Improve

In C language, the <string.h> header file contains the Standard String Library that contains some useful and commonly used string manipulation functions. In this article, we will see how to compare strings in C using the function strcmp().

What is strcmp() in C?

C strcmp() is a built-in library function that is used for string comparison. This function takes two strings (array of characters) as arguments, compares these two strings lexicographically, and then returns 0,1, or -1 as the result. It is defined inside <string.h> header file with its prototype as follows:

Syntax of strcmp() in C

strcmp(first_str, second_str );

Parameters of strcmp() in C

This function takes two strings (array of characters) as parameters:

  • first_str: First string is taken as a pointer to the constant character (i.e. immutable string).
  • second_str: Second string is taken as a pointer to a constant character.

Note: The reason arguments are taken as const char * instead of only char * is so that the function could not modify the string and also make them applicable for constant strings.

Return Value of strcmp() in C

The strcmp() function returns three different values after the comparison of the two strings which are as follows:

1. Zero ( 0 )

A value equal to zero when both strings are found to be identical. That is, all of the characters in both strings are the same.

2. Greater than Zero ( > 0 )

A value greater than zero is returned when the first not-matching character in first_str has a greater ASCII value than the corresponding character in second_str or we can also say that if the character in first_str is lexicographically after the character of second_str, then zero is returned.

3. Lesser than Zero ( < 0 )

A value less than zero is returned when the first not-matching character in first_str has a lesser ASCII value than the corresponding character in second_str. We can also say that if the character in first_str is lexicographically before the character of second_str, zero is returned.

To know more about ASCII values, refer to this article – ASCII Table

How to use the strcmp() function in C

The following example demonstrates how to use the strcmp() function in C:

C
// C Program to Demonstrate the use of strcmp() function#include <stdio.h>#include <string.h>int main(){ // declaring two same string char* first_str = "Geeks"; char* second_str = "Geeks"; // printing the strings printf("First String: %s\n", first_str); printf("Second String: %s\n", second_str); // printing the return value of the strcmp() printf("Return value of strcmp(): %d", strcmp(first_str, second_str)); return 0;}

Output

First String: GeeksSecond String: GeeksReturn value of strcmp(): 0

How strcmp() in C works?

C strcmp() function works by comparing the two strings lexicographically. It means that it compares the ASCII value of each character till the non-matching value is found or the NULL character is found. The working of the C strcmp() function can be described as follows:

1. It starts with comparing the ASCII values of the first characters of both strings.

2. If the first characters in both strings are equal, then this function will check the second character, if they are also equal, then it will check the third, and so on till the first unmatched character is found or the NULL character is found.

3. If a NULL character is found, the function returns zero as both strings will be the same.

strcmp() in C - GeeksforGeeks (1)

4. If a non-matching character is found,

  • If the ASCII value of the character of the first string is greater than that of the second string, then the positive difference ( > 0) between their ASCII values is returned.

strcmp() in C - GeeksforGeeks (2)

  • If the ASCII value of the character of the first string is less than that of the second string, then the negative difference ( < 0) between their ASCII values is returned.

strcmp() in C - GeeksforGeeks (3)

All of these three cases are demonstrated in the below examples.

Examples of strcmp() in C

Example 1. strcmp() behavior for identical strings

This program illustrates the behavior of the strcmp() function for identical strings.

C
// C program to illustrate// strcmp() function#include<stdio.h>#include<string.h>int main(){  char first_str[] = "g f g"; char second_str[] = "g f g";  // Using strcmp() int res = strcmp(first_str, second_str);  if (res==0) printf("Strings are equal"); else printf("Strings are unequal");  printf("\nValue returned by strcmp() is: %d" , res); return 0;}

Output

Strings are equalValue returned by strcmp() is: 0

Example 2. strcmp() behavior for the lexicographically greater first string

The below example demonstrates the strcmp() function behavior for the lexicographically greater first string.

C
// C program to illustrate// strcmp() function#include<stdio.h>#include<string.h>int main(){ // z has greater ASCII value than g char first_str[] = "zfz"; char second_str[] = "gfg";  int res = strcmp(first_str, second_str);  if (res==0) printf("Strings are equal"); else printf("Strings are unequal");  printf("\nValue of result: %d" , res);  return 0;}

Output

Strings are unequalValue of result: 19

Example 3. strcmp() behavior for the lexicographically smaller first string.

The below example demonstrates the strcmp() function behavior for the lexicographically smaller first string.

C
// C program to illustrate// strcmp() function#include<stdio.h>#include<string.h>int main(){ // b has less ASCII value than g char first_str[] = "bfb"; char second_str[] = "gfg";  int res = strcmp(first_str, second_str);  if (res==0) printf("Strings are equal"); else printf("Strings are unequal");  printf("\nValue returned by strcmp() is: %d" , res);   return 0;}

Output

Strings are unequalValue returned by strcmp() is: -5

Conclusion

In this article, we discussed the C standard library function strcmp() which is used to compare two strings lexicographically. The standard library contains some useful and frequently used functions that make programming easier as they help to avoid rewriting the commonly used function again and again when needed.

C strcmp() – FAQs

How can we compare two strings in C?

We can use the strcmp() function which is defined inside <string.h> header file to lexicographically compare two strings (array of characters).

What is the function prototype of strcmp() in C?

The function prototype of the strcmp() function is as follows:

int strcmp(const char* lhs, const char* rhs);

When strcmp() function return zero?

The strcmp() function returns zero when the two strings are identical.

What does the positive return value by the strcmp() function mean?

The strcmp() function returns a positive value when the first string is lexicographically greater than the second string.

What does the negative return value of the strcmp() function mean?

The negative value return by the strcmp() function means that the first string is lexicographically smaller than the second string.

How does the strcmp() function compare two strings in C?

The strcmp() function compares the ASCII values of each character of the two strings till the non-matching character or NULL character is found.

Can the strcmp() function be used to compare non-string data types in C?

No, the strcmp() function cannot compare non-string data types in C. It can only compare the mutable or immutable string data type terminating with a NULL character.

Related Articles:

  • Strings in C
  • Commonly used String functions in C/C++ with Examples


strcmp() in C - GeeksforGeeks (4)

GeeksforGeeks

strcmp() in C - GeeksforGeeks (5)

Improve

Next Article

strcpy in C

Please Login to comment...

strcmp() in C - GeeksforGeeks (2024)
Top Articles
Irreversibility | thermodynamics
Elliottwavecount — Indicatori e segnali — TradingView
El Paso Pet Craigslist
Valley Fair Tickets Costco
Nfr Daysheet
San Diego Terminal 2 Parking Promo Code
PGA of America leaving Palm Beach Gardens for Frisco, Texas
Elle Daily Horoscope Virgo
Cranberry sauce, canned, sweetened, 1 slice (1/2" thick, approx 8 slices per can) - Health Encyclopedia
2016 Hyundai Sonata Price, Value, Depreciation & Reviews | Kelley Blue Book
6001 Canadian Ct Orlando Fl
Flower Mound Clavicle Trauma
This Modern World Daily Kos
Gon Deer Forum
Xomissmandi
The best TV and film to watch this week - A Very Royal Scandal to Tulsa King
Scout Shop Massapequa
Graphic Look Inside Jeffrey Dahmer
Heart Ring Worth Aj
Company History - Horizon NJ Health
HP PARTSURFER - spare part search portal
Lininii
Lawrence Ks Police Scanner
Tokioof
Donald Trump Assassination Gold Coin JD Vance USA Flag President FIGHT CIA FBI • $11.73
Homewatch Caregivers Salary
Grand Teton Pellet Stove Control Board
Navigating change - the workplace of tomorrow - key takeaways
Kelly Ripa Necklace 2022
Joey Gentile Lpsg
Skyward Marshfield
Engr 2300 Osu
How to Quickly Detect GI Stasis in Rabbits (and what to do about it) | The Bunny Lady
'Guys, you're just gonna have to deal with it': Ja Rule on women dominating modern rap, the lyrics he's 'ashamed' of, Ashanti, and his long-awaited comeback
814-747-6702
Rush Copley Swim Lessons
Tricare Dermatologists Near Me
Brake Pads - The Best Front and Rear Brake Pads for Cars, Trucks & SUVs | AutoZone
Brown launches digital hub to expand community, career exploration for students, alumni
Timothy Warren Cobb Obituary
Perc H965I With Rear Load Bracket
Hawkview Retreat Pa Cost
Iman Fashion Clearance
Ts In Baton Rouge
Zeeks Pizza Calories
A rough Sunday for some of the NFL's best teams in 2023 led to the three biggest upsets: Analysis
Spn 3464 Engine Throttle Actuator 1 Control Command
Sleep Outfitters Springhurst
Razor Edge Gotti Pitbull Price
Helpers Needed At Once Bug Fables
Nfsd Web Portal
Bones And All Showtimes Near Emagine Canton
Latest Posts
Article information

Author: Mr. See Jast

Last Updated:

Views: 6415

Rating: 4.4 / 5 (55 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Mr. See Jast

Birthday: 1999-07-30

Address: 8409 Megan Mountain, New Mathew, MT 44997-8193

Phone: +5023589614038

Job: Chief Executive

Hobby: Leather crafting, Flag Football, Candle making, Flying, Poi, Gunsmithing, Swimming

Introduction: My name is Mr. See Jast, I am a open, jolly, gorgeous, courageous, inexpensive, friendly, homely person who loves writing and wants to share my knowledge and understanding with you.