简体   繁体   中英

Compare two std::strings in c++

Is this comparison possible to do in C++?

std::string name = "John";

if (name == "Tom")
   flag = true;
else
   flag = false;

Yes it is, because std::string overloads operator == for const char* .

Alternatively, you can just write

flag = name == "Tom";

or use std::string::compare (returns 0 if the strings match)

To compare srtings in c++, I recommend you to use STRCMP from:

#include <string.h>
....
STRCMP(name,"Tom"); // This will return 0 if they are equal

so you should use it as:

if (STRCMP(name,"Tom")==0)
  flag = true;
else
  flag = false;

remember to use #include < string.h>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM