在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

更新於:17-Dec-2019

396 次瀏覽

開啟您的職業生涯

完成課程並獲得認證

開始吧
廣告
© . All rights reserved.