将substring()的endIndex减1的原因 [英] Reason for subtracting substring()'s endIndex by 1

查看:112
本文介绍了将substring()的endIndex减1的原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
为什么来自索引的是包含在内的,但最终索引是专有的?/a>

Possible Duplicate:
why from index is inclusive but end index is exclusive?

substring()方法=> 字符串substring(int beginIndex,int endIndex)

说明:

返回一个新字符串,该字符串是该字符串的子字符串.首先整数参数指定第一个字符的索引.这第二个整数参数是最后一个字符的索引-1.

Returns a new string that is a substring of this string. The first integer argument specifies the index of the first character. The second integer argument is the index of the last character - 1.

看看下面的代码:

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的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆