Open In App

Case-Insensitive String Comparison in C++

In C++, strings are sequences of characters that are used to store text data which can be in both uppercase and lowercase format. In this article, we will learn how we can compare two case-insensitive strings in C++.

Example:

Input: 
string1 = "WELCOME TO GEEKS FOR GEEKS"
string2 = "welcome to geeks for geeks"

Output:
Strings are equal

Case-Insensitive String Comparison in C++

To compare two case-insensitive strings in C++, we have to temporarily convert both strings to either lowercase or uppercase. After that, we can compare them to get the result which will not depend upon the case of the characters.

Approach

C++ Program for Case-Insensitive String Comparison

The following program illustrates how we can compare two case-insensitive strings in C++:

// C++ Program to illustrate how we can compare two
// case-insensitive strings
#include <cctype>
#include <iostream>
#include <string>
using namespace std;

// Function to check if two case insensitive strings are
// equal or not
bool compareStrings(string& str1, string& str2)
{
    if (str1.length() != str2.length())
        return false;

    for (int i = 0; i < str1.length(); ++i) {
        if (tolower(str1[i]) != tolower(str2[i]))
            return false;
    }

    return true;
}

int main()
{
    // Declare two strings
    string str1 = "WELCOME TO GEEKS FOR GEEKS";
    string str2 = "welcome to geeks for geeks";

    // Check if they are equal or not
    if (compareStrings(str1, str2))
        cout << "Strings are equal" << endl;
    else
        cout << "Strings are not equal " << endl;

    return 0;
}

Output
Strings are equal

Time complexity: O(N), where N denotes the length of the two strings.
Auxiliary Space: O(1)



Article Tags :