Write your own strcmp that ignores cases in C++


Here, we have to create a strcmp (string compare) function that compares two string but ignores cases of the characters of the string. The function will return -1 if string1 < string2, 0 if string1 = string2, 1 if string1 > string2.

Let’s take an example to understand the problem,

Input

string1 = “Hello” , string2 = “hello”

Output

0

To create our own strcmp function that ignores cases while comparing the strings. We will iterate through all characters of both the strings, if characters at ith index are the same i.e. string1[i] == string2[i], continue. If string1[i] > string2[i], return 1. If string1[i] < string2[i], return -1. If the string ends returns 0.

Here, we have to ignore cases, so A and a will be considered the same. We will use the ASCII values of the characters, then ASCII for a = 97 will be equal to ASCII of A = 65.

Program to show the implementation of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
int strcmpFunc(string string1, string string2){
   int i;
   for (i = 0; string1[i] && string2[i]; ++i){
      if (string1[i] == string2[i] || (string1[i] ^ 32) == string2[i])
         continue;
      else
      break;
   }
   if (string1[i] == string2[i])
      return 0;
   if ((string1[i] | 32) < (string2[i] | 32))
      return -1;
   return 1;
}
int main(){
   cout<<"Compareing string using our strcmp function :\n";
   cout<<"Result: "<<strcmpFunc("HELLO", "hello")<<endl;
   cout<<"Result: "<<strcmpFunc("", "Hello")<<endl;
   cout<<"Result: "<<strcmpFunc("Tutorials", "Pint")<<endl;
   cout<<"Result: "<<strcmpFunc("afdadsa", "rewf")<<endl;
   cout<<"Result: "<<strcmpFunc("tutorialspoint", "TUTORIALSpoint")<<endl;
   return 0;
}

Output

Compareing string using our strcmp function −
Result: 0
Result: -1
Result: 1
Result: -1
Result: 0

Updated on: 17-Apr-2020

629 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements