C++如何比較兩個字符串或string是否相等strcmp()和compare()
如果要比較的對象是char字符串
則利用函數(shù)
strcmp(const char s1,const char s2)
- 當(dāng) str1 < str2 時,返回為負(fù)數(shù)(-1);
- 當(dāng) str1 == str2 時,返回值= 0;
- 當(dāng) str1 > str2 時,返回正數(shù)(1)。
注:strcmp(const char s1,const char s2) 這里面只能比較字符串,即可用于比較兩個字符串常量,或比較數(shù)組和字符串常量,不能比較數(shù)字等其他形式的參數(shù)。
代碼示例
#include<iostream>
#include<string>
using namespace std;
int main()
{
char str1[10000];
char str2[10000];
cout << "兩個字符串比較是否相同" << endl;
cout << "請輸入第一個字符串:" << endl;
cin.get(str1, 10000).get();
cout << "請輸入第二個字符串:" << endl;
cin.get(str2, 10000).get();
if (strcmp(str1, str2) == 0)
{
cout << "您輸入的兩個字符串相同" << endl;
}
else
{
cout << "您輸入的兩個字符串不相同" << endl;
}
system("pause");
return 0;
}
運行結(jié)果


如果要比較的對象是兩個string
則利用函數(shù) compare()
若要比較string s1和s2則寫為:s1.compare(s2),若返回值為0,則兩者相等。
- 當(dāng)s1 < s2時,返回為負(fù)數(shù)(-1);
- 當(dāng)s1 == s2時,返回值= 0;
- 當(dāng)s1 > s2時,返回正數(shù)(1)。
代碼示例
#include<iostream>
#include<string>
using namespace std;
int main()
{
char str1[10000];
char str2[10000];
string s1;
string s2;
cout << "兩個字符串比較是否相同" << endl;
cout << "請輸入第一個字符串:" << endl;
cin.get(str1, 10000).get();
cout << "請輸入第二個字符串:" << endl;
cin.get(str2, 10000).get();
s1 = str1;
s2 = str2;
if ( (s1.compare(s2)) == 0 )
{
cout << "您輸入的兩個字符串相同" << endl;
}
else
{
cout << "您輸入的兩個字符串不相同" << endl;
}
system("pause");
return 0;
}


總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
一篇文章讓你輕松理解C++中vector和list區(qū)別
對于學(xué)c語言的同學(xué)來說,vector和list這兩個東西經(jīng)常會搞錯,下面這篇文章主要給大家介紹了關(guān)于C++中vector和list區(qū)別的相關(guān)資料,需要的朋友可以參考下2022-01-01
解析在main函數(shù)之前調(diào)用函數(shù)以及對設(shè)計的作用詳解
本篇文章是對在main函數(shù)之前調(diào)用函數(shù)以及對設(shè)計的作用進行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
C語言字符串函數(shù),字符函數(shù),內(nèi)存函數(shù)使用及模擬實現(xiàn)
這篇文章主要介紹了C語言字符串函數(shù),字符函數(shù),內(nèi)存函數(shù)使用及模擬實現(xiàn),文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09
C語言實現(xiàn)統(tǒng)計字符串單詞數(shù)
這篇文章主要介紹了C語言實現(xiàn)統(tǒng)計字符串單詞數(shù),代碼非常的簡潔,有需要的小伙伴快來參考下。2015-03-03

