java string类字符串查找实现
时间: 2024-04-30 21:17:57 浏览: 13
Java中的String类提供了多种方法来查找字符串,下面介绍几种常用的方法:
1. indexOf() 方法:返回指定子字符串在原字符串中第一次出现的位置。如果没有找到匹配的字符串,则返回-1。
```
String str = "Hello World";
int index = str.indexOf("World");
System.out.println(index); // 输出:6
```
2. lastIndexOf() 方法:返回指定子字符串在原字符串中最后一次出现的位置。如果没有找到匹配的字符串,则返回-1。
```
String str = "Hello World";
int index = str.lastIndexOf("l");
System.out.println(index); // 输出:9
```
3. contains() 方法:判断原字符串是否包含指定的子字符串。
```
String str = "Hello World";
boolean contains = str.contains("World");
System.out.println(contains); // 输出:true
```
4. matches() 方法:判断原字符串是否匹配指定的正则表达式。
```
String str = "Hello World";
boolean matches = str.matches("Hello.*");
System.out.println(matches); // 输出:true
```
5. startsWith() 方法:判断原字符串是否以指定的子字符串开头。
```
String str = "Hello World";
boolean startsWith = str.startsWith("Hello");
System.out.println(startsWith); // 输出:true
```
6. endsWith() 方法:判断原字符串是否以指定的子字符串结尾。
```
String str = "Hello World";
boolean endsWith = str.endsWith("World");
System.out.println(endsWith); // 输出:true
```