Case-insensitive string comparison in C++


In C++ we have strings in standard library. In this program we will see how to check whether two strings are identical or not. In this case we will ignore the case.

Here the logic is simple. We will convert the whole string into lowercase or uppercase strings, then compare them, and return the result.

We have used the algorithm library to get the transform function to convert the string into lowercase string.

Input: Two strings “Hello WORLD” and “heLLO worLD”
Output: Strings are same

Algorithm

Step 1: Take two strings str1, and str2
Step 2: Convert str1, and str2 into lowercase form
Step 3: Compare str1 and str2
Step 4: End

Example Code

 Live Demo

#include<iostream>
#include <algorithm>
using namespace std;
int case_insensitive_match(string s1, string s2) {
   //convert s1 and s2 into lower case strings
   transform(s1.begin(), s1.end(), s1.begin(), ::tolower);
   transform(s2.begin(), s2.end(), s2.begin(), ::tolower);
   if(s1.compare(s2) == 0)
      return 1; //The strings are same
   return 0; //not matched
}
main() {
   string s1, s2;
   s1 = "Hello WORLD";
   s2 = "heLLO worLD";
   if(case_insensitive_match(s1, s2)) {
      cout << "Strings are same";
   }else{
      cout << "Strings are not same";
   }
}

Output

Strings are same

Updated on: 30-Jul-2019

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements