c++string字符串的比較是否相等問(wèn)題
c++string字符串的比較是否相等
最近遇到一個(gè)點(diǎn),在c++中和Java很不一樣,就是Java中string的比較必須是str1.equal(str2),如果采用str1==str2,則是永真式(記不清到底永真還是永假來(lái)著)。
而在c++中,似乎并沒(méi)有equal這個(gè)方法,string的比較也很簡(jiǎn)單,直接通過(guò)str1==str2比較即可。
詳見(jiàn)下方示例
#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++判斷兩個(gè)字符串是否相等
#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 是一樣的
這是正確的
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
高效實(shí)現(xiàn)整型數(shù)字轉(zhuǎn)字符串int2str的方法
下面小編就為大家?guī)?lái)一篇高效實(shí)現(xiàn)整型數(shù)字轉(zhuǎn)字符串int2str的方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-03-03C++11新特性之右值引用與完美轉(zhuǎn)發(fā)詳解
C++11標(biāo)準(zhǔn)為C++引入右值引用語(yǔ)法的同時(shí),還解決了一個(gè)短板,即使用簡(jiǎn)單的方式即可在函數(shù)模板中實(shí)現(xiàn)參數(shù)的完美轉(zhuǎn)發(fā)。本文就來(lái)講講二者的應(yīng)用,需要的可以參考一下2022-09-09