java中判断字符串包含
时间: 2023-11-03 18:05:23 浏览: 40
可以使用String类的contains方法来判断一个字符串是否包含另一个字符串。例如:
```
String str1 = "hello world";
String str2 = "world";
if(str1.contains(str2)){
System.out.println("str1包含str2");
}
```
输出结果为:str1包含str2
相关问题
java判断字符串包含字符串
在Java中,可以使用两种方法来判断一个字符串是否包含另一个字符串:contains()方法和indexOf()方法。
contains()方法是一个boolean类型的方法,用于判断字符串中是否包含指定的字符或子字符串。如果包含,则返回true;如果不包含,则返回false。
indexOf()方法则用于查找一个字符或子字符串在字符串中第一次出现的索引位置。如果找到了指定字符或子字符串,则返回它在字符串中的索引;如果未找到,则返回-1。
因此,如果要判断一个字符串是否包含另一个字符串,可以使用以下代码:
String str = "Hello World";
String subStr = "World";
if(str.contains(subStr)){
System.out.println("字符串包含指定的子字符串");
}else{
System.out.println("字符串不包含指定的子字符串");
}
或者使用indexOf()方法来判断:
String str = "Hello World";
String subStr = "World";
if(str.indexOf(subStr) != -1){
System.out.println("字符串包含指定的子字符串");
}else{
System.out.println("字符串不包含指定的子字符串");
}
java 判断字符串包含字符串
以下是Java中判断字符串是否包含另一个字符串的方法:
1. 使用contains()方法
```java
String str1 = "hello world";
String str2 = "world";
if(str1.contains(str2)){
System.out.println("str1包含str2");
} else {
System.out.println("str1不包含str2");
}
```
2. 使用indexOf()方法
```java
String str1 = "hello world";
String str2 = "world";
if(str1.indexOf(str2) != -1){
System.out.println("str1包含str2");
} else {
System.out.println("str1不包含str2");
}
```
注意:contains()方法是JDK1.5之后才有的,如果使用的是JDK1.4或更早的版本,则只能使用indexOf()方法。
相关推荐
![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)