c++中对于标准库string类型和字面字符串能否直接比较???

2025年03月19日 03:55
有2个网友回答
网友(1):

可以直接比较
str=="abc" 为真,因为是相同的。
上式等价于 "abc"==str
string str2(‘a’); 是错误的,strin构造函数无法将字符型转为字符串。
应该为 string str2('a',100); //100个a
str2==’a‘ 是错误的,不能将字符类型和字符数组类型比较。
str2=="a" 和前面是一个道理。
string 类型和C字符串类型直接比较就行了,重载了运算符的。

网友(2):

可以的.string 使用非常方便
比如
std::string s1="hello world";
std::string s2="hello boy";
const char *cc1="hello girl";
const char *cc2="hello dog";

if (s1==cc1) {.....} //这是可以的
if (s1==s2) {.....}//这是可以的
if (cc1==cc2) {....}//这是错误的
if(strcmp(cc1==cc2)) {....}//这是可以的