c++string字符串的比较是否相等问题
作者:25zhixun
这篇文章主要介绍了c++string字符串的比较是否相等问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
c++string字符串的比较是否相等
最近遇到一个点,在c++中和Java很不一样,就是Java中string的比较必须是str1.equal(str2),如果采用str1==str2,则是永真式(记不清到底永真还是永假来着)。
而在c++中,似乎并没有equal这个方法,string的比较也很简单,直接通过str1==str2比较即可。
详见下方示例
#include <iostream>
#include <string>
using namespace std;
int main()
{
if("abc"=="abc")
{
cout<<"abc等于abc"<<endl;
}
else
{
cout<<"abc不等于abc"<<endl;
}
if("abc"=="ab")
{
cout<<"abc等于ab"<<endl;
}
else
{
cout<<"abc不等于ab"<<endl;
}
string str1="abc",str2="abc",str3="ab";
if(str1==str2)
{
cout<<str1<<"等于"<<str2<<endl;
}
else
{
cout<<str1<<"不等于"<<str2<<endl;
}
if(str1==str3)
{
cout<<str1<<"等于"<<str3<<endl;
}
else
{
cout<<str1<<"不等于"<<str3<<endl;
}
return 0;
}
c++判断两个字符串是否相等
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main()
{
string str1 = "abc", str2 = "abc";
if ( strcmp( str1.c_str(), str2.c_str() ) == 0 )
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}#include <string>
#include <string.h>
#include <iostream>
using namespace std;
string t1 = "helloWorld";
string t2 = "helloWorld";
int main(){
if (t1 == t2)
{
cout<<"***t1 ,t2 是一样的\n";
cout<<"这是正确的\n";
}
// error
if (t1.c_str() == t2.c_str())
{
cout<<"@@@t1 ,t2 是一样的\n";
}
// error
if (t1.c_str() == "helloWorld")
{
cout<<"===t1 ,t2 是一样的\n";
}
if (strcmp(t1.c_str(),t2.c_str()) == 0)
{
cout<<"###t1 ,t2 是一样的\n";
cout<<"这是正确的\n";
}
return 0;
}输出:
***t1 ,t2 是一样的
这是正确的
###t1 ,t2 是一样的
这是正确的
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
