
string.substring() 方法详解
在 Java 中,String 类提供了多种方法来操作字符串,其中 substring() 方法是用于获取字符串的一个子串。这个方法非常有用,特别是在需要处理部分字符串数据时。下面是对 substring() 方法的详细解释和示例。
方法签名
substring() 方法有两种形式:
从指定索引开始到字符串末尾
public String substring(int beginIndex)从指定起始索引到结束索引(不包括结束索引)
public String substring(int beginIndex, int endIndex)
参数说明
- beginIndex: 子字符串的起始位置(包含)。索引从0开始。
- endIndex (可选): 子字符串的结束位置(不包含)。索引从0开始。
返回值
返回一个新的字符串,该字符串是此字符串的一个子字符串。
异常
- 如果 beginIndex 为负,或者大于或等于当前字符串的长度,会抛出 StringIndexOutOfBoundsException。
- 如果 endIndex 大于当前字符串的长度,或者 beginIndex 大于 endIndex,也会抛出 StringIndexOutOfBoundsException。
使用示例
示例一:从一个索引开始到字符串末尾
public class SubstringExample { public static void main(String[] args) { String str = "Hello, World!"; // 从索引7开始到字符串末尾 String result = str.substring(7); System.out.println(result); // 输出: World! } }示例二:从一个索引开始到另一个索引(不包括结束索引)
public class SubstringExample { public static void main(String[] args) { String str = "Hello, World!"; // 从索引0开始到索引5(不包括索引5) String result = str.substring(0, 5); System.out.println(result); // 输出: Hello } }注意事项
- 不可变性: 由于 String 在 Java 中是不可变的,因此每次调用 substring() 都会返回一个新的字符串对象。原始字符串不会被修改。
- 性能考虑: 对于长字符串且频繁进行子字符串操作时,需要考虑内存使用和垃圾回收的影响。在某些情况下,使用 StringBuilder 或 StringBuffer 可能更高效。
- 边界条件: 确保提供的索引值在有效范围内,以避免抛出 StringIndexOutOfBoundsException。
通过理解并正确使用 substring() 方法,你可以高效地处理和操作字符串数据。
