0

Can anyone pls let me know the exact c++ code of case sensitive comparison function of string class?

7
  • 4
    @Aman Saleem: What is wrong with the == operator? Commented Aug 10, 2010 at 10:23
  • 4
    case sensitive or case insensitive? Commented Aug 10, 2010 at 10:24
  • Please give your questions more descriptive titles -- "C++ Object Oriented Programming" is way too generic. I've gone in and done this one for you. Commented Aug 10, 2010 at 10:24
  • String comparison is case sensitive by default. Just use operator== for std::string. Commented Aug 10, 2010 at 10:36
  • Kirill, can u pls let me the code? Commented Aug 10, 2010 at 10:40

4 Answers 4

5

How about?

std::string str1, str2;
/* do stuff to str1 and str2 */
if (str1 == str2) { /* do something */ }

Or

if (str1.compare(str2) == 0) { /* the strings are the same */ }
Sign up to request clarification or add additional context in comments.

Comments

4
std::string str1("A new String");
std::string str2("a new STring");
if(str1.compare(str2) == 0)
    std::cout<<"Equal";     // str1("A new String") str2("A new String");
else 
    std::cout<<"unEqual";   //str1("A new String") str2("a new STring") 

compare() returns an integral value rather than a boolean value. Return value has the following meaning: 0 means equal, a value less than zero means less than, and a value greater than zero means greater than

2 Comments

Can u pls give the code in output of that the str1 is equal to str2 if both strings are equal & give the output that str1 is not equal to str2 if both the string are not equal?
Why would you use compare rather than operator== ?
2

== is overloaded for string comparison in C++ AFAIK (unlike in Java, where u have to use myString.equals(..))

If you want to ignore case when comparing, just convert both strings to upper or lower case as explained here: Convert a String In C++ To Upper Case

Comments

1
#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string str1 ("green apple");
  string str2 ("red apple");

  if (str1.compare(str2) != 0)
    cout << str1 << " is not " << str2 << "\n";

  if (str1.compare(6,5,"apple") == 0)
    cout << "still, " << str1 << " is an apple\n";

  if (str2.compare(str2.size()-5,5,"apple") == 0)
    cout << "and " << str2 << " is also an apple\n";

  if (str1.compare(6,5,str2,4,5) == 0)
    cout << "therefore, both are apples\n";

  return 0;
}

I got it from http://www.cplusplus.com/reference/string/string/compare/

Hope google work !!

But use == operator like s1 == s2 would also work good

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.