substring(int beginIndex)
这个方法截取的字符串是从索引beginIndex开始的,到整个字符串的末尾,
abcde
索引: 01234
从第2个开始,索引:2 开始
结果是cde
substring(int beginIndex, int endIndex)
这个方法截取的字符串从beginIndex开始,到字符串索引的endIndex - 1结束,
即截取的字符串不包括endIndex这个索引对应的字符,
abcde
索引: 01234
substring(2, 4)
从索引2开始 到索引‘4-1’ 可以得到
cd
使用这个方法的时候 substring(int beginIndex, int endIndex) 需要特别注意容易发生字符串截取越界的问题
endIndex的最大值为整个字符串的长度,
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(s.substring(2, 4));
System.out.println(s.substring(2));
/*
* 字符串:abcde
*
* 索引: 01234
*
*/
/*
* 结果:
* cd
* cde
*/
sc.close();
}
}