关于java substring()的注意事项
用了好久的s.substring();今天突然发现还有一些坑之前不知道。先列举一下substring()的三种用法。
- a.substring(start,end);
public class test01 {
public static void main(String[] args) {
String a="abcdef";
System.out.println(a.substring(0,2));
System.out.println(a.substring(0,a.length()));
}
}
输出结果1:ab
输出结果2 : abcdef
注意点1:当为两个参数时,参数为下标索引,并且为左闭右开。右边界可以为a.length()。
- a.substring(start);
public class test01 {
public static void main(String[] args) {
String a="abcdef";
System.out.println(a.substring(0));
System.out.println(a.substring(1));
}
}
输出结果1:abcdef
输出结果2 : bcdef
- 以上几点其实答主之前都是会的,今天在做算法题的时候遇到的另一种情况,具体题目就不贴了,我把其中我关于substring困惑的地方贴出来,供大家注意。
public class test01 {
public static void main(String[] args) {
String a="abcdef";
System.out.println(a.substring(a.length()));
}
}
我第一反应这样的写法是错误的,应该是error,因为我一直认为,左参数一定是要小于a.length()的,但是这个的输出结果是空字符串,后来我看了一下源码,向大家解释一下
public String substring(int beginIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
int subLen = value.length - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
总结来说,无论是一个参数还是两个参数,参数的范围是0<=start<=end<=a.length();一个参数的a.substring(start)等于a.substring(start,a.length()),同理,上述System.out.println(a.substring(a.length()));可以写成System.out.println(a.substring(a.length(),a.length()));根据左闭右开,所以是空字符串。