Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Problem
1.1.
Example
2.
Solution
2.1.
Implementation
3.
Using compare()
3.1.
Implementation
4.
Using C strcmp()
4.1.
Implementation
5.
Using strncmp()
5.1.
Implementation
6.
Time Complexity
7.
Space Complexity
8.
FAQs
9.
Key Takeaways
Last Updated: Mar 27, 2024

String compare in C

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Problem

Given two strings A and B, write a program to string compare in C. Return 0 if both the strings are equal, >0 if the first non-matching character of A has a higher ASCII value than the corresponding character in B, and <0 if the first non-matching character has a smaller ASCII value than the corresponding character in B.

Example

Input

A = “abc”, B = “abc”

Output

0

Explanation

Both the strings are equal. Hence the string compare in C program to compare the two strings returns 0.

Input

A = “abzc”, B = “abcz”

Output

1

Explanation

The first mismatching index is the third index. The corresponding character in A is “z” and in B is “c”. “z” has a greater ASCII value than “c”, hence the string compare in C function returns a number >0.

Solution

There are several ways to string compare in C/C++. First, we will look at comparing two strings by defining our own function. We can iterate over the strings and check if they mismatch at any index. If they mismatch and A[i] > B[i] at that index, it means that the first string is greater than the second, else the second string is greater than the first.

If the strings do not mismatch, we will check if both the strings are of the same size or not. If both the strings are of the same size, the string compare in C will return 0, else if the size of A is greater than B, we will return 1, else -1.

Implementation

#include <bits/stdc++.h>
using namespace std;

// C program to compare the two strings
int compare(string a, string b){

    // Iterating over min(len(A), len(B))
    for(int i = 0; i < min(a.length(), b.length()); i++){

        // A[i]>B[i] means A is lexicographically greater
        if (a[i] > b[i]){
            return 1;
        }

        // A[i]<B[i] means B is lexicographically greater
        else if (a[i] < b[i]){
            return -1;
        }
    }

    /*
    If our code reaches here, no character 
    has been mismatched until now.
    Now we will compare two strings by length.
    */
    if (a.length() != b.length()){
        return (a.size()>b.size());
    }

    // If lengths are also same, return 0
    return 0;
}

// Driver Code
int main(){
    string a = "abzc";
    string b = "abcz";
    cout<<compare(a,b)<<endl;
}

Output

1

Also see : C Static Function, 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

Using compare()

C++ standard library has an inbuilt function std::string::compare() to string compare in C character by character. It returns the following three types of values:

0, If both the strings are equal.

>0, If the first string is lexicographically greater than the second.

<0, If the second string is lexicographically greater than the first.

Implementation

#include <bits/stdc++.h>
using namespace std;

// C program to compare the two strings
int main(){
    string a = "abzc";
    string b = "abcz";
    cout<<a<<' '<<b<<' '<<a.compare(b)<<endl;

    a = "abcz";
    b = "abzc";
    cout<<a<<' '<<b<<' '<<a.compare(b)<<endl;

    a = "abcd";
    b = "abcd";
    cout<<a<<' '<<b<<' '<<a.compare(b)<<endl;
}

Output

abzc abcz 1
abcz abzc -1
abcd abcd 0

Using C strcmp()

C strcmp() is a function to string compare in C. Its output also follows the same rules as compare().

Implementation

#include <bits/stdc++.h>
using namespace std;

// Compare two strings using strcmp()
int main(){
    char a[] = "abzc";
    char b[] = "abcz";
    cout<<strcmp(a,b)<<endl;
}

Have a look also on strcat() function in C and Short int in C Programming

Must Read Passing Arrays to Function in C

Using strncmp()

std::strncmp() takes three arguments - String A, String B, Integer N. It is used to string compare in C for maximum N characters. It first compares the first characters of both the strings. If the characters are the same, it compares the second character and so on. If at any position, the characters mismatch, it returns the answer accordingly. This process stops if either the null-character (\0) is encountered in any string or it has made N comparisons.

Implementation

#include <bits/stdc++.h>
using namespace std;

// String compare in C using strncmp()
int main(){
    char a[] = "abzc";
    char b[] = "abcz";
    cout<<strncmp(a,b,3)<<endl;
}

For better understanding try it on online C compiler.

Time Complexity

To string compare in C, we need to check the first character where these strings mismatch. To do these, we iterate over the minimum length of both strings. Therefore the time complexity to string compare in C is O(min(length(A), length(B))).

Space Complexity

For comparing two strings, we just need to use some variables. Therefore, the space complexity is O(1).

Must Read Decision Making in C

FAQs

  1. What is the return value of C strcmp()?
    C Strcmp() is an inbuilt function that compares two strings (character arrays) in C/C++. It returns 0 if both the strings are equal, >0 if the ASCII value of the first character where both the strings mismatch is greater in the first string, and <0 if it is greater in the second string.
  2. How does C strcmp() function work?
    Strcmp() function is used to string compare in C two strings character by character. If the first character in both the strings is the same, then it compares the second character and so on until a mismatch is found.
  3. What is the difference between C strcmp() and strncmp()?
    Strcmp() takes two strings as input and compares them by character until a mismatch is found. Strncmp() also does the same thing but only for the first ‘N’ characters, where ‘N’ is the third argument of the function.

Key Takeaways

In this article, we have extensively discussed different ways to string compare in C and their implementation in C++. We hope that this blog has helped you enhance your knowledge on comparing two strings in C++ and if you would like to learn more, check out our articles on Coding Ninjas Studio. Do upvote our blog to help other ninjas grow. Happy Coding!”

Live masterclass