我正在用 Java 做一个编码问题,我的解决方案有效,但我看到其他人在他们的博客上发布了一个不同的解决方案,该解决方案有点短,但我不明白为什么它有效。
问题是:
Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range
0..str.length()-1
inclusive).
我的代码(在所有条件下都有效):
public String missingChar(String str, int n) {
return str.substring(0,n) + str.substring(n+1,str.length());
}
其他也有效的代码是:
public String missingChar(String str, int n) {
return str.substring(0, n) + str.substring(n + 1);
}
区别就在第二行的末尾。
我的问题是为什么 str.substring(n+1)
产生与 str.substring(n+1,str.length())
相同的结果?
最佳答案
substring() 方法有两种变体:
公共(public)字符串子字符串(int beginIndex)
或
public String substring(int beginIndex, int endIndex)
子字符串以指定 beginIndex
处的字符开始,并延伸到该字符串的末尾,或者如果给出了第二个参数,则一直延伸到 endIndex - 1
。
关于java - 为什么这两个子字符串调用等效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26239657/