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)文章
高效實現(xiàn)整型數(shù)字轉(zhuǎn)字符串int2str的方法
下面小編就為大家?guī)硪黄咝崿F(xiàn)整型數(shù)字轉(zhuǎn)字符串int2str的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-03-03
C++11新特性之右值引用與完美轉(zhuǎn)發(fā)詳解
C++11標(biāo)準(zhǔn)為C++引入右值引用語法的同時,還解決了一個短板,即使用簡單的方式即可在函數(shù)模板中實現(xiàn)參數(shù)的完美轉(zhuǎn)發(fā)。本文就來講講二者的應(yīng)用,需要的可以參考一下2022-09-09

