-6

I need some built-in function to compare strings. For C-style strings I have

strcmp();

But I need some function to deal with the string class.

string name1;
string name2;
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
  • http://cplusplus.com/reference/string/string/compare/ – didierc Apr 22 '13 at 06:40
  • -1. If "==" maybe hard to find, just search for title should have revealed at least something - http://www.bing.com/search?q=function+to+compare+string+in+c%2B%2B%3F gives plenty of `string::compare` links. – Alexei Levenkov Apr 22 '13 at 06:40

2 Answers2

10

You're looking for the equality operator, operator==(), which is defined for std::basic_string:

if (name1 == name2)

Other comparison operators are also available, namely !=, <, <=, > and >=.

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
1

You could use std::string::compare() which provides the same functionality as strcmp().

std::string name1 = "John";
std::string name2 = "Micheal";

int result = name1.compare(name2);

Would roughly be the same as:

const char* name1 = "John";
const char* name2 = "Micheal";

int result = std::strcmp(name1, name2);
Mark Garcia
  • 17,424
  • 4
  • 58
  • 94