首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

c++中string比较的有关问题

2012-03-24 
求助c++中string比较的问题C/C++ code #include iostream#include cstdlib#include stringusing nam

求助c++中string比较的问题

C/C++ code
 #include <iostream>#include <cstdlib>#include <string>using namespace std;int main(){    string s1("this"), s2("that");    if("that" == s2){        cout << "match" << endl;    }else{        cout << "not match" << endl;    }        if("this" == s1){        cout << "match" << endl;    }else{        cout << "not match" << endl;    }        if(s1 == s1.c_str()){        cout << "match" << endl;    }else{        cout << "not match" << endl;    }         if("this" == s1.c_str()){        cout << "match" << endl;    }else{        cout << "not match" << endl;    }         system("pause");    return 0;}
 

输出结果是:match
match
match
not match
想请问一下为什么:"this" == s1为true,s1 == s1.c_str()为true,"this" == s1.c_str()是false呢?

[解决办法]
"this" 和 s1.c_str()的比较需要使用strcmp函数,单纯的用==比较的实质是两个字符串的首地址
[解决办法]
if(s1 == s1.c_str()){ //这里是调用什么来比较
cout << "match" << endl;
}else{
cout << "not match" << endl;


if("this" == s1.c_str()){ //strcmp函数即可
cout << "match" << endl;
}else{
cout << "not match" << endl;





探讨

"this" 和 s1.c_str()的比较需要使用strcmp函数,单纯的用==比较的实质是两个字符串的首地址

[解决办法]
楼上正解,strcmp情何以堪啊
[解决办法]
basic_string::compare
int compare(const basic_string& str) const;
int compare(size_type p0, size_type n0,
const basic_string& str);
int compare(size_type p0, size_type n0,
const basic_string& str, size_type pos, size_type n);
int compare(const E *s) const;
int compare(size_type p0, size_type n0,
const E *s) const;
int compare(size_type p0, size_type n0,
const E *s, size_type pos) const;
Each member function compares up to n0 elements of the controlled sequence beginning with position p0, or the entire controlled sequence if these arguments are not supplied, to the operand sequence. The function returns:

A negative value if the first differing element in the controlled sequence compares less than the corresponding element in the operand sequence (as determined by T::compare), or if the two have a common prefix but the operand sequence is longer. 
Zero if the two compare equal element by element and are the same length. 
A positive value otherwise. 

[解决办法]
不建议使用==判断比较字符串。
使用strcmp吧
[解决办法]
探讨
basic_string::compare
int compare(const basic_string&amp; str) const;
int compare(size_type p0, size_type n0,
const basic_string&amp; str);
int compare(size_type p0, size_type n0,
const basic……

热点排行