在Java中,substring() 方法用于从字符串中提取子字符串。这个方法有两种常用的形式:

  1. substring(int beginIndex):从指定的起始索引 beginIndex 开始,提取到字符串的末尾。
  2. 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
}
}

注意事项

  1. 索引从0开始:字符串的索引从0开始计数。
  2. 边界检查:如果 beginIndex 或 endIndex 超出字符串的长度范围,或者 beginIndex 大于 endIndex,将会抛出 StringIndexOutOfBoundsException 异常。
  3. 负数索引: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() 方法时,务必确保索引值在合法范围内,以避免抛出异常。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部