java中字符串定位子串
时间: 2023-04-10 09:03:05 浏览: 96
可以使用 String 类的 indexOf() 方法来定位子串在字符串中的位置,例如:
String str = "hello world";
int index = str.indexOf("world");
System.out.println(index); // 输出 6
这里的 indexOf() 方法返回的是子串在字符串中第一次出现的位置,如果没有找到则返回 -1。
相关问题
java字符串包含子串
在Java中,你可以使用`contains()`方法来判断一个字符串是否包含另一个子串。这个方法返回一个布尔值,表示是否找到了子串。
下面是一个示例代码:
```java
String mainString = "Hello, world!";
String subString = "world";
if (mainString.contains(subString)) {
System.out.println("主字符串包含子串");
} else {
System.out.println("主字符串不包含子串");
}
```
在上面的例子中,`contains()`方法用于检查`mainString`是否包含`subString`。如果包含,就打印"主字符串包含子串",否则打印"主字符串不包含子串"。
注意,`contains()`方法是区分大小写的。如果你想要忽略大小写,可以使用`toLowerCase()`方法将字符串转换为小写再进行比较。例如:
```java
String mainString = "Hello, world!";
String subString = "WORLD";
if (mainString.toLowerCase().contains(subString.toLowerCase())) {
System.out.println("主字符串包含子串");
} else {
System.out.println("主字符串不包含子串");
}
```
这样就会忽略大小写进行比较了。
java 字符串截取子串
要截取Java字符串的子串,可以使用`substring()`方法。这个方法接受两个参数,分别是起始索引和终止索引(不包括),返回一个新的字符串,包含指定范围内的字符。
下面是一个示例代码:
```java
String str = "Hello World";
String subStr = str.substring(6, 11); // 从索引6开始,到索引11之前(不包括)的字符
System.out.println(subStr); // 输出 "World"
```
如果只指定起始索引而不指定终止索引,则返回从起始索引开始到字符串末尾的子串。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.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)