在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.