string 比较
时间: 2023-07-23 22:07:26 浏览: 44
在 C++ 中,可以使用 `==` 运算符来比较两个字符串是否相等。例如:
```c++
#include <iostream>
#include <string>
int main() {
std::string str1 = "hello";
std::string str2 = "world";
if (str1 == str2) {
std::cout << "str1 equals str2" << std::endl;
} else {
std::cout << "str1 does not equal str2" << std::endl;
}
return 0;
}
```
输出结果为:
```
str1 does not equal str2
```
需要注意的是,如果要比较两个字符串是否相等,一定要使用 `==` 运算符,而不是 `=` 赋值运算符。
相关问题
java string比较大小
在Java中,可以使用String类的compareTo()方法来比较两个字符串的大小。该方法返回一个整数值,如果字符串相等,则返回0;如果当前字符串小于另一个字符串,则返回负数;如果当前字符串大于另一个字符串,则返回正数。
例如,比较两个字符串"abc"和"def"的大小:
```
String str1 = "abc";
String str2 = "def";
int result = str1.compareTo(str2);
System.out.println(result); // 输出负数,表示str1小于str2
```
std::string比较
在C++中,可以使用`==`运算符来比较两个`std::string`对象是否相等。如果两个对象的内容相同,则返回`true`,否则返回`false`。例如:
```c++
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello";
std::string str2 = "World";
if (str1 == str2) {
std::cout << "str1 and str2 are equal." << std::endl;
} else {
std::cout << "str1 and str2 are not equal." << std::endl;
}
return 0;
}
```
输出结果为:
```
str1 and str2 are not equal.
```
需要注意的是,`compare`方法和`strcmp`并不相同,它比较的是`std::string`的`size()`大小里的所有字节。在`size()`长度范围里,如果有`\0`字符,一样进行比较。所以在不知道`std::string`里是否存储纯字符串时,最好先转换为`const char*`(调用`c_str()`),再调用`strcmp`比较。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)