C ++中的字符串类是用于管理字符串的容器,它比普通的c字符串具有许多优点。在许多编程问题中,我们需要比较两个字符串,在本文中,我们讨论用于比较C ++中两个字符串类对象的库函数。
我们使用std::string::compare()函数比较两个字符串对象。如果两个字符串相等,则返回“ 0”;如果比较的字符串较短,则返回整数<0;如果比较的字符串较长,则返回整数> 0。我们可以根据需要以各种形式使用std::string::compare()函数,下面讨论一些方法。
引用: std::string::compare()
范例1:
语法:
string::compare (const string& str) const
#include<iostream>
using namespace std;
int main() {
string s1("includehelp");
string s2("include");
string s3("includehelp");
if((s1.compare(s2)) == 0)
cout << s1 << " is equal to " << s2 << endl;
else
cout << s1 << " didn't match to " << s2 << endl;
if((s1.compare(s3)) == 0)
cout << s1 << " is equal to " << s3 << endl;
else
cout << s1 << " didn't match to " << s3 << endl;
return 0;
}输出结果
includehelp didn't match to include includehelp is equal to includehelp