std::string 与字符串比较函数
时间: 2023-08-02 10:07:55 浏览: 56
在 C++ 中,可以使用 `std::string` 类型来表示字符串。`std::string` 类型有一个成员函数 `compare()` 用于比较两个字符串。其语法如下:
```c++
int compare(const std::string& str) const;
```
该函数将当前字符串与参数 `str` 进行比较,返回值为整数,含义如下:
- 如果当前字符串小于 `str`,返回负数;
- 如果当前字符串等于 `str`,返回零;
- 如果当前字符串大于 `str`,返回正数。
使用示例:
```c++
#include <iostream>
#include <string>
int main() {
std::string str1 = "hello";
std::string str2 = "world";
int result = str1.compare(str2);
if (result < 0) {
std::cout << "str1 is less than str2" << std::endl;
} else if (result == 0) {
std::cout << "str1 is equal to str2" << std::endl;
} else {
std::cout << "str1 is greater than str2" << std::endl;
}
return 0;
}
```
输出结果为:
```
str1 is less than str2
```