在Java中,substring()
方法用于从字符串中提取子字符串。这个方法有两种常用的形式:
substring(int beginIndex)
:从指定的起始索引beginIndex
开始,提取到字符串的末尾。substring(int beginIndex, int endIndex)
:从指定的起始索引beginIndex
开始,提取到指定的结束索引endIndex
(不包括endIndex
位置的字符)。
以下是这两种用法的详细说明和示例代码:
1. substring(int beginIndex)
语法:
java复制代码
public String substring(int beginIndex) |
参数:
beginIndex
:提取子字符串的起始索引(包含该索引位置的字符)。
返回值:
- 从
beginIndex
开始到字符串末尾的子字符串。
示例:
java复制代码
public class SubstringExample { |
|
public static void main(String[] args) { |
|
String str = "Hello, World!"; |
|
String result = str.substring(7); |
|
System.out.println(result); // 输出:World! |
|
} |
|
} |
2. substring(int beginIndex, int endIndex)
语法:
java复制代码
public String substring(int beginIndex, int endIndex) |
参数:
beginIndex
:提取子字符串的起始索引(包含该索引位置的字符)。endIndex
:提取子字符串的结束索引(不包含该索引位置的字符)。
返回值:
- 从
beginIndex
开始到endIndex
之前的子字符串。
示例:
java复制代码
public class SubstringExample { |
|
public static void main(String[] args) { |
|
String str = "Hello, World!"; |
|
String result = str.substring(7, 12); |
|
System.out.println(result); // 输出:World |
|
} |
|
} |
注意事项
- 索引从0开始:字符串的索引从0开始计数。
- 边界检查:如果
beginIndex
或endIndex
超出字符串的长度范围,或者beginIndex
大于endIndex
,将会抛出StringIndexOutOfBoundsException
异常。 - 负数索引:
substring
方法不支持负数索引,使用负数索引会抛出StringIndexOutOfBoundsException
异常。
示例:异常处理
java复制代码
public class SubstringExample { |
|
public static void main(String[] args) { |
|
String str = "Hello, World!"; |
|
try { |
|
// 可能会抛出 StringIndexOutOfBoundsException |
|
String result = str.substring(7, 20); |
|
System.out.println(result); // 输出:World!(但这里只会输出到末尾,因为20超出范围,但只会忽略超出部分) |
|
} catch (StringIndexOutOfBoundsException e) { |
|
System.out.println("索引超出范围: " + e.getMessage()); |
|
} |
|
try { |
|
// 一定会抛出 StringIndexOutOfBoundsException |
|
String result = str.substring(-1, 5); |
|
System.out.println(result); |
|
} catch (StringIndexOutOfBoundsException e) { |
|
System.out.println("索引不能是负数: " + e.getMessage()); |
|
} |
|
} |
|
} |
在实际开发中,使用 substring()
方法时,务必确保索引值在合法范围内,以避免抛出异常。