Wednesday 24 March 2010

Case-Insensitive String comparison

It is often a problem that we ask someone to input some string for comparison but they often put different case and the comparison fails. For example if we are expecting a string, say, 'true'. The user may input 'True' or 'TRUE'. A simple comparison will fail in this case.

The following is a simple program to convert the input string to lower case. What this would allow is to do a case-insensitive search.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<string>

using namespace
std;

//First approach for converting into lower case
string toLowerString(string& input)
{

int
length = input.length();
string output;
for
(int i = 0; i < length; i++)
{

output += tolower(input[i]);
}

return
output;
}


//Second approach for converting into lower case
string toLowerString(string& input, bool approach2) //Overloaded method
{
int
length = input.length();
string output;
for
(int i = 0; i < length; i++)
{

if
(input[i] >= 0x41 && input[i] <= 0x5A) //Ascii for A-Z
output += (input[i] + 0x20); //ascii for a-z
else
output += input[i];
}

return
output;
}


int
main()
{

string s1="true";
string s2("TRUE");
string s3;
s3 = "True";

//Check if s1 = s2
if(s1 == s2)
cout<<"s1 == s2"<<endl;
else

cout<<"s1 != s2"<<endl;

//Check if s1 = s2 with first approach
if(s1 == toLowerString(s2))
cout<<"s1 == Approach1::toLowerString(s2)"<<endl;
else

cout<<"s1 != Approach1::toLowerString(s2)"<<endl;

//Check if s1 = s2 with second approach
if(s1 == toLowerString(s2,true))
cout<<"s1 == Approach2::toLowerString(s2)"<<endl;
else

cout<<"s1 != Approach2::toLowerString(s2)"<<endl;


//Check if s1 = s3 with second approach
if(s1 == s3)
cout<<"s1 == s3"<<endl;
else

cout<<"s1 != s3"<<endl;

if
(s1 == toLowerString(s3,true))
cout<<"s1 == Approach2::toLowerString(s3)"<<endl;
else

cout<<"s1 != Approach2::toLowerString(s3)"<<endl;

//Check if s1 = s3 with second approach
if(s1 == toLowerString(s3))
cout<<"s1 == Approach1::toLowerString(s3)"<<endl;
else

cout<<"s1 != Approach1::toLowerString(s3)"<<endl;

return
0;
}





The output is as follows:


I am aure much better approaches are possible. If you have a better example please share.

3 comments:

  1. You can avoid all the hassle of converting to lower case before comparing by doing a case in-sensitive comparison by using _stricmp

    ReplyDelete
  2. Yes, I forgot about __stricmp. I am not sure if this is portable and will work in all different compilers/OS.

    __stricmp works fine with VC++.

    ReplyDelete
  3. Thanks, it's really simple. Especially when i compare the other sites which also include string comparision algorithms about that issue.

    ReplyDelete