问题描述
substring()
方法=> 字符串substring(int beginIndex,int endIndex)
说明:
看看下面的代码:
String anotherPalindrome = "Niagara. O roar again!";
String roar = anotherPalindrome.substring(11, 15);
输出:咆哮
现在,如果JVM没有将 int endIndex
减一,我们可以只使用 substring(11,14)
,那不会更多方便且不易出错(人为方面)?如果您没有仔细阅读说明,当您认为 endIndex
只是正常索引时,您可能会花半个小时(就像我一样)挠头.Java语言创建者将其减去1的原因是什么?
Now, if the JVM didn't substract int endIndex
by one, we could just use substring(11,14)
instead, wouldn't that be much more convenient and less error-prone (human side)? Had you not read the description carefully, you might just ended up scratching your head for half an hour (like I did) when you thought that endIndex
is just the normal index. What's the reason for the Java language creators to subtract it by one?
推荐答案
它有几个优点:
s.substring(0, s.length())
总是正确的.另外:
s.substring(i, j)
结果字符串的大小始终为 j-i
.更具体地说, s.substring(0,j)
将始终返回 j
个字符.最后,这意味着,如果要在索引 i
之后使用 n
个字符,您只需说:
The size of resulting string is always j - i
. More specifically s.substring(0, j)
will always return j
characters. Finally this means that if you want to take n
characters after index i
you simply say:
s.substring(i, i + n)
提取字符串的后缀(最后的 n
个字符)也更容易:
It's also easier to extract suffix of a string (last n
characters):
s.substring(s.length() - n, s.length())
例如,提取文件扩展名:
For example extracting file extension:
s.substring(s.indexOf('.') + 1, s.length())
这篇关于将substring()的endIndex减1的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!