gpt4 book ai didi

java - 为什么 substring() 函数应该返回溢出消息却返回值

转载 作者:行者123 更新时间:2023-12-01 23:21:33 25 4
gpt4 key购买 nike

我正在尝试解决这样的问题:-

给定一个字符串,返回“向左旋转 2”版本,其中前 2 个字符移至末尾。字符串长度至少为 2。

left2("Hello") → "lloHe"
left2("java") → "vaja"
left2("Hi") → "Hi"

我为此编写了两个函数:-

    public String left2(String str)
{
String str1 = str;
if(str.length()>2)
str1 = str.substring(2)+str.substring(0,2);
return str1;
}

public String left2(String str)
{
return str.substring(2)+str.substring(0,2);
}

两个函数都是正确的。我想知道如果 substring() 函数的第一个参数是索引,那么我在第二个函数中是否不会收到 overflow 错误?我问这个是因为 Java 不以 NULL 字符结尾,所以我认为第二个函数中有错误。

最佳答案

这是因为您的子字符串逻辑仅在文本长度大于 2 时才起作用。请参见此处:

    if(str.length()>2)
str1 = str.substring(2)+str.substring(0,2);

这是java中substring方法的源代码:

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);
}

根据经验,文档可能会说谎,但代码不会。 StringIndexOutOfBoundsException 仅在以下情况下抛出:

  • a. beginIndex 小于 0(即为负数)或
  • b. endIndex 大于 count 或
  • c. beginIndex 大于 endIndex。

关于java - 为什么 substring() 函数应该返回溢出消息却返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20558447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com