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 Beginner FOR Beginner"
string2 = "welcome to Beginner for Beginner"

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

  • Check if the lengths of both the strings are equal or not. If not return false.
  • Iterate through each character of both strings.
  • Convert each character to lowercase format using std::tolower method.
  • If any character is different return false.
  • If all characters were same return true.

C++ Program for Case-Insensitive String Comparison

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

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 Beginner FOR Beginner";
    string str2 = "welcome to Beginner for Beginner";

    // 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)




Contact Us