此函数将字符串对象的值与其参数指定的字符序列进行比较。
假设str1和str2是两个字符串,我们想比较这两个字符串,则其语法应类似于:
int k= str1.compare(str2);
#include<iostream> using namespace std; void main() { string str1="Hello"; string str2="learnfk"; 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包含值" learnfk",我们使用compare方法比较这两个字符串,并且此compare方法始终返回整数值。当我们比较这两个字符串时,得到的值小于零。现在,在这种情况下如果条件失败,则else语句将运行并显示"Both the strings are unequal"。
#include<iostream> using namespace std; void main() { string str1="Welcome to learnfk"; string str2="Welcome to learnfk"; int i=str1.compare(str2); if(i==0) cout<<"strings are equal"; else cout<<"strings are not equal"; }
输出:
Strings are equal
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)