Java - “String index out of range” exception

前端 未结 5 1984
再見小時候
再見小時候 2021-01-16 04:14

I wrote this little function just for practice, but an exception (\"String index out of range: 29\") is thrown and I don\'t know why...

(I know this isn\'t the best

5条回答
  •  臣服心动
    2021-01-16 05:03

    a much better implementation (with regex) is simply return y.replaceAll("\\s+"," "); (this even replaces other whitespace)

    and StringBuffer.length() is constant time (no slow null termination semantics in java)

    and similarly x.charAt(x.length()); will also throw a StringIndexOutOfBoundsException (and not return \0 like you'd expect in C)

    for the fixed code:

    while ( y.length()>i)//use length from the buffer
    {
        if (y.charAt(i) != ' ')
        {
            y.setCharAt(j, y.charAt(i));
            i++;
            j++;
        }
        else
        {
            y.setCharAt(j, y.charAt(i));
            i++;
            j++;
            while (y.charAt(i) == ' ')
                i++;
        }           
    }
    y.setLength(j);//using setLength to actually set the length
    

    btw a StringBuilder is a faster implementation (no unnecessary synchronization)

提交回复
热议问题