比较C++中的两个字符串

给定两个字符串,如何检查这两个字符串是否相等。 例如:

null
Input  : ABCD, XYZOutput : ABCD is not equal to XYZ         XYZ is greater than ABCDInput  : Geeks, forGeeksOutput : Geeks is not equal to forGeeks         forGeeks is greater than Geeks

这个问题可以用以下两种方法中的任何一种来解决

  • C++关系运算符

CPP

// CPP code to implement relational
// operators on string objects
#include <iostream>
using namespace std;
void relationalOperation(string s1, string s2)
{
if (s1 != s2)
{
cout << s1 << " is not equal to " << s2 << endl;
if (s1 > s2)
cout << s1 << " is greater than " << s2 << endl;
else
cout << s2 << " is greater than " << s1 << endl;
}
else
cout << s1 << " is equal to " << s2 << endl;
}
// Driver code
int main()
{
string s1( "Geeks" );
string s2( "forGeeks" );
relationalOperation(s1, s2);
string s3( "Geeks" );
string s4( "Geeks" );
relationalOperation(s3, s4);
return 0;
}


输出

Geeks is not equal to forGeeksforGeeks is greater than GeeksGeeks is equal to Geeks

  • std::Compare()

CPP

// CPP code perform relational
// operation using compare function
#include <iostream>
using namespace std;
void compareFunction(string s1, string s2)
{
// comparing both using inbuilt function
int x = s1.compare(s2);
if (x != 0) {
cout << s1
<< " is not equal to "
<< s2 << endl;
if (x > 0)
cout << s1
<< " is greater than "
<< s2 << endl;
else
cout << s2
<< " is greater than "
<< s1 << endl;
}
else
cout << s1 << " is equal to " << s2 << endl;
}
// Driver Code
int main()
{
string s1( "Geeks" );
string s2( "forGeeks" );
compareFunction(s1, s2);
string s3( "Geeks" );
string s4( "Geeks" );
compareFunction(s3, s4);
return 0;
}


输出

Geeks is not equal to forGeeksforGeeks is greater than GeeksGeeks is equal to Geeks

C++关系运算符与COMPAREARE()之间的差异:

  1. compare()返回int,而关系运算符返回布尔值,即true或false。
  2. 单个关系运算符对于特定操作是唯一的,而compare()可以根据传递的参数类型单独执行许多不同的操作。
  3. 我们可以使用compare()比较给定字符串中任何位置的任何子字符串,否则需要使用关系运算符逐字提取字符串以进行比较的漫长过程。

例如:-

  • 使用compare()
// Compare 3 characters from 3rd position// (or index 2) of str1 with 3 characters // from 4th position of str2. if (str1.compare(2, 3, str2, 3, 3) == 0)   cout<<"Equal";else   cout<<"Not equal";
  • 使用关系运算符
for (i = 2, j = 3; i <= 5 && j <= 6; i++, j++)    {     if (s1[i] != s2[j])       break;}if (i == 6 && j == 7)    cout << "Equal";else    cout << "Not equal";

上面的例子清楚地说明了 比较 减少了大量额外处理,因此建议在某些位置执行子字符串比较时使用它,否则两者的执行方式几乎相同。

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享