java中字符串比较实例
时间: 2024-06-15 10:06:46 浏览: 15
在Java中,字符串比较可以使用以下几种方式:
1. 使用equals()方法进行比较:
```java
String str1 = "Hello";
String str2 = "World";
if (str1.equals(str2)) {
System.out.println("str1和str2相等");
} else {
System.out.println("str1和str2不相等");
}
```
输出结果为:"str1和str2不相等"。equals()方法会比较两个字符串的内容是否相等。
2. 使用compareTo()方法进行比较:
```java
String str1 = "Hello";
String str2 = "World";
int result = str1.compareTo(str2);
if (result == 0) {
System.out.println("str1和str2相等");
} else if (result < 0) {
System.out.println("str1小于str2");
} else {
System.out.println("str1大于str2");
}
```
输出结果为:"str1小于str2"。compareTo()方法会按照字典顺序比较两个字符串,返回一个整数值,表示两个字符串的大小关系。
3. 使用equalsIgnoreCase()方法进行忽略大小写比较:
```java
String str1 = "Hello";
String str2 = "hello";
if (str1.equalsIgnoreCase(str2)) {
System.out.println("str1和str2相等");
} else {
System.out.println("str1和str2不相等");
}
```
输出结果为:"str1和str2相等"。equalsIgnoreCase()方法会忽略字符串的大小写进行比较。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)