C++ String compare()
C++ String compare()
此函数将字符串对象的值与其参数指定的字符序列进行比较。
语法:
假设str1和str2是两个字符串,我们要比较这两个字符串,则其语法应类似于:
int k= str1.compare(str2);
k == 0: 如果k包含零值,则意味着两个字符串相等。
k != 0: 如果k确实包含零值,则意味着两个字符串都不相等。
k > 0: 如果k包含大于零的值,则比较字符串中第一个字符的值较大,或者所有比较字符匹配,但比较字符串较长。
k < 0: 如果k包含小于零的值,则比较字符串中第一个字符的值较低,或者所有比较字符都匹配,但比较字符串较短。
示例1
#include<iostream>
using namespace std;
void main()
{
string str1="Hello";
string str2="lidihuo";
int k= str1.compare(str2);
if(k==0)
cout<<"Both the strings are equal";
else
cout<<"Both the strings are unequal";
}
输出:
Both the strings are unequal
请考虑两个字符串str1和str2、 str1包含值" Hello",str2包含值" lidihuo",我们使用compare方法比较这两个字符串,并且此compare方法始终返回整数值。当我们比较这两个字符串时,得到的值小于零。现在,在这种情况下如果条件失败,则else语句将运行并显示"两个字符串都不相等"。
示例2
#include<iostream>
using namespace std;
void main()
{
string str1="Welcome to lidihuo";
string str2="Welcome to lidihuo";
int i=str1.compare(str2);
if(i==0)
cout<<"strings are equal";
else
cout<<"strings are not equal";
}
输出: