alf*_*sin -3 java string substring
请考虑以下情形:
String str = "str";
System.out.println("str subs: " + str.substring(3,3));
Run Code Online (Sandbox Code Playgroud)
预期结果:(
StringIndexOutOfBoundsException因为beginIndex在"字符串结束后"开始)
实际结果:
打印空字符串
来自String.java:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
Run Code Online (Sandbox Code Playgroud)
可以很容易地看到,实现不搭边情况下的护理:
beginIndex == endIndex == count (count是字符串的长度).
根据手册的方法子串:
返回一个新字符串,该字符串是此字符串的子字符串.子字符串从指定的beginIndex开始,并扩展到索引endIndex - 1处的字符.因此子字符串的长度为endIndex-beginIndex.
它还声明该方法抛出:
IndexOutOfBoundsException - 如果beginIndex为负数,或者endIndex大于此String对象的长度,或者beginIndex大于endIndex.
考虑案例是否有意义:beginIndex == endIndex == count有效吗?
我错过了什么吗?
"abc".substring(3,3) == ""
Run Code Online (Sandbox Code Playgroud)
如你所说,让我们看一下手册:
返回一个新字符串,该字符串是此字符串的子字符串.
好的
子字符串从指定的beginIndex开始,并扩展到索引endIndex - 1处的字符.
无论弦的长度如何,这句话的解释都很困难.但我认为我们可以同意空字符串不会违反这一点.
因此子串的长度是endIndex-beginIndex.
好的
抛出:IndexOutOfBoundsException - 如果beginIndex为负数
它不是
或endIndex大于此String对象的长度
它不是
或者beginIndex大于endIndex.
它不是.
行为似乎是对我的承诺.
你也可以这样看:字符串"abc"包含四个空子串,两个字符之间,一个在开头,一个在结尾.他们可以通过以下方式访问substring同1,1和2,2,0,0和3,3分别.还要与以下代码比较
class EmptyTest {
public static void main (String[] args) {
Matcher m = Pattern.compile("").matcher("abc");
while (m.find()) {
System.out.println(m.start() + "," + m.end());
}
}
}
Run Code Online (Sandbox Code Playgroud)
打印
0,0
1,1
2,2
3,3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2056 次 |
| 最近记录: |