1)我们比较常用的是比较运算符
String 类的常见运算符包括 >、<、==、>=、<=、!=。
示例代码:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str1 = "DEF";
string str2 = "ABC";
if(str1<str2)
cout<<"str2 is bigger";
else if(str1>str2)
cout<<"str1 is bigger";
else
cout<<"they are the same";
return 0;
}
读者应注意,对于参加比较的两个字符串,任一个字符串均不能为 NULL,否则程序会异常退出。
2)Basic_string 类模板提供了 compare() 函数,支持多参数处理。该函数返回一个整数来表示比较结果。如果相比较的两个子串相同,compare() 函数返回 0,否则返回非零值。
compare() 的原型如下:
int compare (const basic_string& s) const;
int compare (const Ch* p) const;
int compare (size_type pos, size_type n, const basic_string& s) const;
int compare (size_type pos, size_type n, const basic_string& s,size_type pos2, size_type n2) const;
int compare (size_type pos, size_type n, const Ch* p, size_type = npos) const;
示例代码:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string A ("aBcdef");
string B ("AbcdEf");
int m=A.compare (B); //完整的A和B的比较
int n=A.compare(1,5,B,4,2); //"Bcdef"和"Ef"比较
cout << "m = " << m <<", n = " << n << endl;
cin.get();
return 0;
}
执行结果为: m = 1, n = -1