在Java中,String 类提供了一个 substring(int beginIndex) 和 substring(int beginIndex, int endIndex) 方法,用于从字符串中提取子字符串。这两个方法的行为略有不同,但都基于字符的索引来提取子字符串。
1. substring(int beginIndex)
这个方法接受一个参数 beginIndex,它表示子字符串的起始索引(包含)。该方法将返回从 beginIndex 开始到原字符串末尾的子字符串。
注意:beginIndex 必须在字符串的索引范围内,即 0 <= beginIndex <= string.length()。如果 beginIndex 等于字符串的长度,那么返回的字符串将是空的。
2. substring(int beginIndex, int endIndex)
这个方法接受两个参数:beginIndex(子字符串的起始索引,包含)和 endIndex(子字符串的结束索引,不包含)。该方法将返回从 beginIndex 开始到 endIndex - 1 的子字符串。
注意:
beginIndex必须小于endIndex。beginIndex和endIndex都必须在字符串的索引范围内,即0 <= beginIndex <= endIndex <= string.length()。- 如果
endIndex等于字符串的长度,那么endIndex实际上指向的是字符串末尾的下一个位置(即字符串外的位置),因此返回的子字符串将不包括endIndex位置的字符。
示例
public class SubstringExample {
public static void main(String[] args) {
String str = "Hello, World!";
// 使用 substring(int beginIndex)
String sub1 = str.substring(7);
System.out.println(sub1); // 输出: World!
// 使用 substring(int beginIndex, int endIndex)
String sub2 = str.substring(0, 5);
System.out.println(sub2); // 输出: Hello
// 注意:如果beginIndex或endIndex超出范围,将抛出StringIndexOutOfBoundsException
// String sub3 = str.substring(12, 15); // 这将抛出异常,因为endIndex超出了字符串的长度
}
}
在上面的示例中,substring 方法被用来从字符串 "Hello, World!" 中提取子字符串。第一个调用提取了从索引 7 开始到字符串末尾的子字符串 "World!"。第二个调用提取了从索引 0 开始到索引 5(不包含索引 5)的子字符串 "Hello"。
1789

被折叠的 条评论
为什么被折叠?



