开发者

Case sensitive string comparison in C++

开发者 https://www.devze.com 2023-01-11 10:40 出处:网络
Can anyone pls let me know th开发者_Python百科e exact c++ code of case sensitive comparison function of string class? How about?

Can anyone pls let me know th开发者_Python百科e exact c++ code of case sensitive comparison function of string class?


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 */ }


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


== 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


#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

0

精彩评论

暂无评论...
验证码 换一张
取 消