Java的substring()
方法从字符串中提取一部分(子字符串)并返回它。
示例
class Main {
public static void main(String[] args) {
String str1 = "java is fun";
// extract substring from index 0 to 3
System.out.println(str1.substring(0, 4));
}
}
// Output: java
substring() 语法
string.substring(int startIndex, int endIndex)
substring() 参数
substring()
方法最多可以接受两个参数。
- startIndex - 起始索引
- endIndex (可选) - 结束索引
substring() 返回值
substring()
方法返回给定字符串的子字符串。
- 子字符串从 startIndex 处的字符开始,一直延伸到 endIndex - 1 处的字符。
- 如果未传递 endIndex,则子字符串从指定索引处的字符开始,一直延伸到字符串的末尾。

注意:如果出现以下情况,您将收到错误:
- startIndex/endIndex 为负数或大于字符串长度
- startIndex 大于 endIndex
示例 1:仅带起始索引的 Java substring()
class Main {
public static void main(String[] args) {
String str1 = "program";
// 1st character to the last character
System.out.println(str1.substring(0)); // program
// 4th character to the last character
System.out.println(str1.substring(3)); // gram
}
}
示例 2:带起始和结束索引的 Java substring()
class Main {
public static void main(String[] args) {
String str1 = "program";
// 1st to the 7th character
System.out.println(str1.substring(0, 7)); // program
// 1st to the 5th character
System.out.println(str1.substring(0, 5)); // progr
// 4th to the 5th character
System.out.println(str1.substring(3, 5)); // gr
}
}
另请阅读