Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 214
  • Last Modified:

string comparisons

Hi if I define two strings s1,s2 why can't I use strcmp(s1,s2) ?

however I can check if (s1==s2) but what about comparing abel and ABel in this case (s1==s2) doesn't work.

Are there any functions that convert a string to lower case or upper case.

I solved this by using strcmp (s1.c_str(),s2.c_str()) but in case of using long arrays of string won't that be an overhead to covert s1 to s1.c_str()

0
anshuma
Asked:
anshuma
  • 2
3 Solutions
 
IndrawatiCommented:
Simple answer:

#include <algorithm>
(for_each(a.begin(), a.end(), tolower) == for_each(b.begin(), b.end(), tolower))

will do case-insensitive comparison.

For another way to do it, you may look at GoTW #29:
http://www.gotw.ca/gotw/029.htm
0
 
IndrawatiCommented:
Sorry, the last answer should be:

      string a = "ABEL";
      string b = "abel";

      transform(a.begin(), a.end(), a.begin(), tolower);
      transform(b.begin(), b.end(), b.begin(), tolower);
      cout << a == b;

I confused transform() with for_each()... again.
0
 
Jaime OlivaresCommented:
> I solved this by using strcmp (s1.c_str(),s2.c_str()) but in case of using long arrays of string won't that be an overhead
> to covert s1 to s1.c_str()
Actually there is not conversion, just some **arrangements** to give you a pointer to the string buffer, ensuring it is null terminated to be handled correctly by functions like strcmp() or stricmp().

0
 
itsmeandnobodyelseCommented:
std::string isn't very comfortable regarding case insensitivity and other regular string functionality. Mostly, it's because std::string is a template class but case sensitivity easily could be handled only for (ASCII) char type.

You may help yourself by defining an own operator== function like that:

bool operator== (const string& s1, const string& s2)
{
    return stricmp(s1.c_str(), s2.c_str()) == 0;
}

The disadvantage is that you've to put the definition to any IDE you or others are working with code depending on that feature.

Regards, Alex


0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now