c++string字符串的比較是否相等問題
更新時間:2023年08月09日 09:09:05 作者: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 是一樣的
這是正確的
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C語言數(shù)據(jù)結(jié)構(gòu)實例講解單鏈表的實現(xiàn)
單鏈表是后面要學(xué)的雙鏈表以及循環(huán)鏈表的基礎(chǔ),要想繼續(xù)深入了解數(shù)據(jù)結(jié)構(gòu)以及C++,我們就要奠定好這塊基石!接下來就和我一起學(xué)習(xí)吧2022-03-03
Visual?C++?6.0添加一個對話框的實現(xiàn)步驟
VC6.0是微軟公司推出的一款集成開發(fā)環(huán)境,本文主要介紹了Visual?C++?6.0添加一個對話框的實現(xiàn)步驟,具有一定的參考價值,感興趣的可以了解一下2024-06-06
C++實現(xiàn)LeetCode(149.共線點個數(shù))
這篇文章主要介紹了C++實現(xiàn)LeetCode(149.共線點個數(shù)),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07

