string字符串比较c++
时间: 2023-11-24 16:53:28 浏览: 138
关于C++ string和c类型字符数组的对比
在C++中,可以使用比较运算符(==、!=、<、>、<=、>=)来比较两个字符串。字符串的比较规则是按顺序先从前往后比较,同序号的字符按照ASCII码值比较,直到遇到对应字符不等或者字符串结束。例如:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "hello";
string str2 = "world";
string str3 = "hello";
if (str1 == str2) {
cout << "str1 is equal to str2" << endl;
} else {
cout << "str1 is not equal to str2" << endl;
}
if (str1 == str3) {
cout << "str1 is equal to str3" << endl;
} else {
cout << "str1 is not equal to str3" << endl;
}
if (str1 < str2) {
cout << "str1 is less than str2" << endl;
} else {
cout << "str1 is not less than str2" << endl;
}
return 0;
}
```
输出结果为:
```
str1 is not equal to str2
str1 is equal to str3
str1 is less than str2
```
阅读全文