Java 根据已知的开头与结尾,截取数据
时间: 2024-04-10 08:27:39 浏览: 33
您可以使用Java的substring()方法来截取已知开头和结尾的数据。该方法通过指定起始索引和结束索引来提取字符串的子字符串。
下面是一个示例代码,展示如何使用substring()方法截取字符串:
```java
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
String start = "Hello";
String end = "!";
// 获取起始索引
int startIndex = str.indexOf(start);
if (startIndex != -1) {
startIndex += start.length();
}
// 获取结束索引
int endIndex = str.indexOf(end);
// 判断索引是否有效,并进行截取
if (startIndex != -1 && endIndex != -1 && startIndex <= endIndex) {
String result = str.substring(startIndex, endIndex);
System.out.println(result);
} else {
System.out.println("无法截取数据");
}
}
}
```
在上述示例中,我们将字符串`"Hello, World!"`赋给变量`str`,并分别将已知的开头字符串`"Hello"`和结尾字符串`"!"`赋给变量`start`和`end`。然后,通过使用`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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)