substring()
String 类中提供了两个重载的 substring() 方法,这是截取字符串最核心、最常用的方法。

substring(int beginIndex)
从指定的索引位置开始,截取到字符串的末尾。
语法:
public String substring(int beginIndex)
参数:
beginIndex: 开始截取的索引(包含该位置的字符),索引从0开始。
返回值:
- 返回一个新的
String对象,包含从beginIndex到末尾的所有字符。
示例:
public class SubstringExample {
public static void main(String[] args) {
String str = "Hello, World!";
// 从索引 7 开始截取,直到末尾
String result = str.substring(7);
System.out.println("原始字符串: " + str); // 输出: Hello, World!
System.out.println("截取结果: " + result); // 输出: World!
}
}
substring(int beginIndex, int endIndex)
从指定的开始索引,截取到指定的结束索引(不包含结束索引处的字符)。
语法:
public String substring(int beginIndex, int endIndex)
参数:
beginIndex: 开始截取的索引(包含该位置的字符)。endIndex: 结束截取的索引(不包含该位置的字符)。
返回值:
- 返回一个新的
String对象,包含从beginIndex到endIndex - 1的所有字符。
示例:
public class SubstringExample {
public static void main(String[] args) {
String str = "Hello, World!";
// 从索引 7 开始,到索引 12 结束(不包含索引12的字符)
String result = str.substring(7, 12);
System.out.println("原始字符串: " + str); // 输出: Hello, World!
System.out.println("截取结果: " + result); // 输出: World
}
}
⚠️ 重要注意事项
索引越界问题
beginIndex或endIndex为负数,或者beginIndex大于字符串的长度,会抛出StringIndexOutOfBoundsException。endIndex大于字符串的长度,也会抛出StringIndexOutOfBoundsException。beginIndex大于endIndex,同样会抛出StringIndexOutOfBoundsException。
示例:
String str = "Java"; // str.substring(5); // 抛出 StringIndexOutOfBoundsException // str.substring(2, 1); // 抛出 StringIndexOutOfBoundsException
字符串不可变性
请务必记住,String 对象在 Java 中是不可变的。substring() 方法不会修改原始字符串,而是返回一个新的字符串对象。
示例:
String original = "I love Java";
String sub = original.substring(2, 6); // sub 的值是 "love"
System.out.println("原始字符串: " + original); // 输出: I love Java (未改变)
System.out.println("截取后的新字符串: " + sub); // 输出: love
其他截取方法(特定场景)
除了 substring(),还有一些其他方法可以实现类似“截取”的功能。
split() + 数组访问
当你需要根据某个分隔符来截取字符串时,split() 方法非常方便,它会返回一个字符串数组,你可以通过索引来访问你想要的“部分”。
语法:
public String[] split(String regex)
示例:
String path = "/usr/local/bin/java";
String[] parts = path.split("/"); // 用 "/" 作为分隔符
// parts 数组内容: ["", "usr", "local", "bin", "java"]
String fileName = parts[parts.length - 1]; // 获取最后一部分
System.out.println("文件名: " + fileName); // 输出: java
String dir = parts[2];
System.out.println("目录: " + dir); // 输出: local
String.format() 或 printf()
虽然这不是严格意义上的“截取”,但如果你需要从字符串的开头或结尾获取固定长度的子串,可以使用格式化字符串来实现。
示例:
String longText = "This is a very long text that we need to shorten.";
// 获取前 10 个字符
String prefix = String.format("%-10.10s", longText); // 左对齐,10个字符宽度
System.out.println("前10个字符: " + prefix); // 输出: This is a v
// 获取后 5 个字符
// 先计算开始索引
int start = longText.length() - 5;
String suffix = longText.substring(start);
System.out.println("后5个字符: " + suffix); // 输出: en.
使用正则表达式 (Pattern 和 Matcher)
对于非常复杂的截取规则(提取所有数字、提取特定格式的文本等),正则表达式是最强大的工具。
示例:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String text = "订单号: ORD-2025-12345, 金额: $99.99";
// 提取订单号
Pattern pattern = Pattern.compile("订单号: (ORD-\\d+-\\d+)");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
String orderNumber = matcher.group(1); // group(0) 是整个匹配,group(1) 是第一个括号捕获的内容
System.out.println("提取的订单号: " + orderNumber); // 输出: ORD-2025-12345
}
总结与最佳实践
| 方法 | 适用场景 | 示例 |
|---|---|---|
substring(beginIndex) |
从指定位置截取到字符串末尾。 | str.substring(7); |
substring(beginIndex, endIndex) |
截取一个指定范围的子串(最常用)。 | str.substring(2, 6); |
split() |
根据分隔符将字符串分割成多部分,然后取其中一部分。 | str.split("/")[2]; |
| 正则表达式 | 根据复杂的模式规则提取或匹配子串。 | Pattern.compile(...).matcher(...).find() |
核心建议:
- 简单截用
substring:如果只是简单地从某个位置开始或结束截取,直接使用substring()是最简单、最高效的选择。 - 按分隔符截用
split:如果你的字符串有明确的分隔符(如逗号、斜杠、空格等),并且你想获取其中某个“字段”,split()是最直观的。 - 复杂规则用正则:如果截取的逻辑非常复杂,比如需要匹配特定格式、忽略大小写、提取嵌套内容等,请毫不犹豫地使用正则表达式。
- 始终注意索引:使用
substring()时,要时刻记住索引从 0 开始,endIndex是不包含的,为了避免StringIndexOutOfBoundsException,最好在调用前检查索引的有效性。
希望这份详细的指南能帮助你熟练掌握 Java 字符串截取!
