java 判断字符串包含字符串
时间: 2024-01-04 17:02:34 浏览: 36
以下是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()方法。
相关问题
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提供了两种方法来判断字符串是否包含某个字符:contains()方法和indexOf()方法。
1. contains()方法:该方法是String类提供的一个非常方便的方法,可以用来判断一个字符串是否包含某个字符。该方法返回一个布尔值,表示目标字符串是否包含指定字符。示例代码如下:
String str = "Hello, World!";
char targetChar = 'o';
if (str.contains(String.valueOf(targetChar))) {
System.out.println("字符串包含字符 '" + targetChar + "'");
} else {
System.out.println("字符串不包含字符 '" + targetChar + "'");
}
2. indexOf()方法:该方法返回指定字符在字符串中第一次出现的位置,如果没有找到该字符,则返回-1。示例代码如下:
String str = "Hello, World!";
char targetChar = 'o';
if (str.indexOf(targetChar) >= 0) {
System.out.println("字符串包含字符 '" + targetChar + "'");
} else {
System.out.println("字符串不包含字符 '" + targetChar + "'");
}
注意:在使用indexOf()方法时,需要将字符转换为字符串类型,可以使用String.valueOf()方法或者直接将字符用单引号括起来。
相关推荐
![](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)