在 C++ 中比較兩個字串
這裡我們將瞭解如何在 C++ 中比較兩個字串。C++ 具有 string 類。它在標準庫中還有 compare() 函式用於比較字串。此函式會逐個字元檢查字串,如果存在某些不匹配,則會返回非零值。讓我們看看程式碼以獲得更好的想法。
示例
#include<iostream>
using namespace std;
void compareStrings(string s1, string s2) {
int compare = s1.compare(s2);
if (compare != 0)
cout << s1 << " is not equal to "<< s2 << endl;
else if(compare == 0)
cout << "Strings are equal";
if (compare > 0)
cout << s1 << " is greater than "<< s2 << " difference is: " << compare << endl;
else if(compare < 0)
cout << s2 << " is greater than "<< s1 << " difference is: " << compare << endl;
}
int main() {
string s1("hello");
string s2("helLo");
compareStrings(s1, s2);
}輸出
hello is not equal to helLo hello is greater than helLo difference is: 1
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP