Open In App

C strcmp()

Last Updated : 29 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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: Geeks
Second String: Geeks
Return 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 with zero as return vlaue

 

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 with positive return value

 

  • 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 with negative return value

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 equal
Value 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 unequal
Value 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 unequal
Value 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:



Similar Reads

Write one line functions for strcat() and strcmp()
Recursion can be used to do both tasks in one line. Below are one line implementations for stracat() and strcmp(). /* my_strcat(dest, src) copies data of src to dest. To do so, it first reaches end of the string dest using recursive calls my_strcat(++dest, src). Once end of dest is reached, data is copied using (*dest++ = *src++)? my_strcat(dest, s
2 min read
Difference between strncmp() and strcmp in C/C++
The basic difference between these two are : strcmp compares both the strings till null-character of either string comes whereas strncmp compares at most num characters of both strings. But if num is equal to the length of either string than strncmp behaves similar to strcmp.Problem with strcmp function is that if both of the strings passed in the
3 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
Pattern Programs in C
Printing patterns using C programs has always been an interesting problem domain. We can print different patterns like star patterns, pyramid patterns, Floyd's triangle, Pascal's triangle, etc. in C language. These problems generally require the knowledge of loops and if-else statements. In this article, we will discuss the following example progra
15+ min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
8 min read
C Programming Interview Questions (2024)
At Bell Labs, Dennis Ritchie developed the C programming language between 1971 and 1973. C is a mid-level structured-oriented programming and general-purpose programming. It is one of the old and most popular programming languages. There are many applications in which C programming language is used, including language compilers, operating systems,
15+ min read
C++ Interview Questions and Answers (2024)
C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent in C++. It is utilized by top IT companies such as
15+ min read
C Hello World Program
The “Hello World” program is the first step towards learning any programming language and also one of the simplest programs you will learn. To print the "Hello World", we can use the printf function from the stdio.h library that prints the given string on the screen. C Program to Print "Hello World"The following C program displays "Hello World" in
2 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations.  As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example,  If there is
9 min read
vector erase() and clear() in C++
Prerequisite: Vector in C++ Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::clear() The clear() function is used to remove all the elements of the vector container, thus making it size 0. Syntax
6 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
9 min read
C++ Data Types
All variables use data type during declaration to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data they can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Every data type
10 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. In this article, we will discuss C pointers in detail, their
14 min read
Convert String to int in C++
Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we can convert numbers that are stored as strings. Exa
8 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
11 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the &lt;map&gt; header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
10 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data type is a collection of data with values having fixed values, meaning
7 min read
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more
15+ min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning. In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot overload in C++. C++ Operator OverloadingC++ has
8 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor
7 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&amp;T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read
Practice Tags :