
在学习Java的过程中,字符串截取是必不可少的一个基础课,几乎所有程序中都会用过字符串截取,拆分的操作方法,在JAVA字符串主要通过 substring() 方法实现。字符串的索引位置从 0 开始,截取操作成功后会返回新字符串)。以下是对字符串截取常用方式详细说明和示例:
方法一:substring(int beginIndex)
截取从 beginIndex 开始到字符串末尾的部分。
- 参数:beginIndex(起始索引,包含该字符)
- 注意:若 beginIndex < 0>= 字符串长度,抛出 StringIndexOutOfBoundsException。
示例:
String str = "Hello, World!";
String sub1 = str.substring(7); // 从索引7开始到末尾
System.out.println(sub1); // 输出: World!
方法二:substring(int beginIndex, int endIndex)
截取从 beginIndex 到 endIndex - 1 之间的子字符串。
- 参数:
- beginIndex(起始索引,包含)
- endIndex(结束索引,不包含)
- 注意:
- 若 beginIndex > endIndex 或索引越界,抛出异常。
- 有效范围:0 ≤ beginIndex ≤ endIndex ≤ 字符串长度。
示例:
String str = "Hello, World!";
String sub2 = str.substring(0, 5); // 截取索引0到4
System.out.println(sub2); // 输出: Hello
String sub3 = str.substring(7, 12); // 截取索引7到11
System.out.println(sub3); // 输出: World
常见的错误及处理方法
- 索引越界:
- String str = "Java";
str.substring(5);
// 抛出
StringIndexOutOfBoundsException,因为截取的位置超出了字符串的长度
- 处理方式:在进行截取前先检查参数有效性。
例如:
if (beginIndex >= 0 && beginIndex <= str.length()) {
// 在范围内可以安全的截取
}else{
System.out.println('' 位置超出了字符串的长度范围了");
}
- 动态截取:结合 indexOf() 定位字符的起始位置
String email = "user@example.com";
int atIndex = email.indexOf('@');
String username = email.substring(0, atIndex);//这里也需要进行判断一下,万一字符不存在呢
System.out.println(username); // 输出: user
5.Windows 下目录的特殊处理
在 Windows 系统中,路径分隔符通常为反斜杠 \,需要注意转义。以下是一个示例:
public class MYTest {
public static void main(String[] args) {
String filePath = "C:\\Program Files\\Java\\jdk-18\\bin\\java.exe";
String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
System.out.println("文件名是=====>" + fileName);
}
}
输出结果:文件名是=====>java.exe
其他截取技巧
- 去除首尾空格:trim()
- String str = " Java ";
- String trimmed = str.trim(); //输出 "Java"
- 按分隔符分割:split()
- String data = "apple,banana,orange";
- String[] fruits = data.split(",",-1);
- //尊敬的您需要重点记得加上 -1 ,否则会导致空格被消除。这个问题常常给新人带来困扰,在笔者的 MES 应用当中,许多功能需要将字符串拆分成数组,而其中是存在空格的。
- // ["apple", "banana", "orange"]
总结
方法 | 参数 | 返回值 | 异常 |
substring(beginIndex) | beginIndex | 从起始索引到末尾 | beginIndex 越界时抛出异常 |
substring(beginIndex, endIndex) | beginIndex, endIndex | 从起始到结束索引前一位 | 参数不合法时抛出异常 |
最佳实践:始终进行验证索引范围,避免发生异常。
根据实际需求灵活组合 substring、indexOf 等方法实现复杂截取逻辑。
本文暂时没有评论,来添加一个吧(●'◡'●)