在 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
广告