Question

Possible Duplicate:
Case insensitive string comparison in C++

I've written some code for a c++ to compare two strings for equality. What I'd like is a proofreading. I'm planning on using this for more programs in the future, so it's important that this function do its job well. Does this function look like one that will be reusable, portable, etc.? Is there a more 'up-to-date' method of doing this? I used a c library but this is a c++ program, is that taboo?

Thanks, JH.

//function to compare two strings regardless of case 
//-- returns true if the two strings are equal
//-- returns false if
//  --the strings are unequal
//  --one of the strings is longer than 255 chars
bool isEqual(string str1, string str2){

  if(str1.length()!=str2.length())  //the strings are different lengths,
    return false;               //they can't be equal
  if((str1.length()>255) || (str2.length()>255))
    return false;

  char * cstr1 = new char [str1.length()+1];
  strcpy (cstr1, str1.c_str());
  char * cstr2 = new char [str2.length()+1];
  strcpy (cstr2, str2.c_str());

  for(int i=0; i<str1.length()+1; i++){
    if(toupper(cstr1[i]) != toupper(cstr2[i]))
      return false;
  }

  return true;
}
Was it helpful?

Solution

You should rename the function to isEqual_CaseInsensitive or something to have a name that matches what the function does. You should pass the strings by reference to avoid a copy You don't need to create a copy of the strings to compare them

    bool isEqual_CaseInsensitive(const string& a, const string& b)
    {
            return a.size() == b.size() &&
                std::equal(a.begin(), a.end(), b.begin(), [](char cA, char cB) {
                        return toupper(cA) == toupper(cB);
                   });
    }

OTHER TIPS

The function looks quite good except that:

These conversions to c strings are not necessary:

  char * cstr1 = new char [str1.length()+1];
  strcpy (cstr1, str1.c_str());
  char * cstr2 = new char [str2.length()+1];
  strcpy (cstr2, str2.c_str());

since you can access of std::string letters like in c string:

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

also note that I removed +1 from i<str1.length() + 1...

For other methods - see there: Case insensitive string comparison in C++

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top