在C++中使用關係運算符比較String物件
在這裡,我們將瞭解如何在 C++ 中比較兩個字串。C++ 具有 string 類。它還具有標準庫中的 compare() 函式來比較字串。但在這裡,我們將使用條件運算子,如 ==、!=、<、>、<=、>=. 這些運算子按字元比較字串。請看程式碼以更好地理解。
示例
#include<iostream>
using namespace std;
void compareStrings(string s1, string s2) {
if (s1 != s2)
cout << s1 << " is not equal to "<< s2 << endl;
else if(s1 == s2)
cout << "Strings are equal";
if (s1 > s2)
cout << s1 << " is greater than "<< s2 << endl;
else if(s1 < s2)
cout << s2 << " is greater than "<< s1 << endl;
}
int main() {
string s1("hello");
string s2("helLo");
compareStrings(s1, s2);
}輸出
hello is not equal to helLo hello is greater than helLo
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP