怎么判断string类型中的值是否相等

来源:百度知道 编辑:UC知道 时间:2024/06/26 03:18:43
比如我定义string si='wohao'
string s2='wohao'
但是我如果用if(s1==s2)
cout<<"相等"<<endl;
else
cout<<"不等"<<endl;
但是结果都是"不等",明明里面值都相同的,不然要该怎么做?
我用了strcmp(s1,s2)结果编译出了问题:i\文件的相似性.cpp(46) : error C2664: 'strcmp' : cannot convert parameter 1 from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'const char *'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

楼主用
string s1 = 'wohao'
这个单引号是用来定义字符变量的,怎么能用来定义string
像char ch1 = 'a';
定义string用双引号嗒像 string str1 = "wohao";

不过那位老兄说"比较他们的首地址",这个我不同意.string类型已经做过了运算符"=="的重载,可以直接str1 == str2的
像:
string str1 = "111",str2 = "111";
bool flag = (str1 == str2);
flag就是true
不过使用string类型的前提是,有:
#include <string>
using namespace std;

!!!!用这个!
if(si.equals(s2))

else
两个字符串之间比较是用equals比较的! 不能用== ==是用还比较int类型的!

L_o_o_n_i_e 说得对,可以用 .c_str() 转换为 c 字符串,再用 strcmp 比较。但是,这样就比较麻烦了,可以用string中的比较函数直接比较就可以了。两种方法如下:
#include<iostream>
#include <string>
using namespace std;
void main()
{
string s1("wohao");
string s2("wohao");
//第一种方法用strcmp
if ( strcmp(s1.c_str(),s2.c_str()) == 0 )
cout << "equal" <<endl;
else
cout<<