Java - exception "String index out the range"

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

(I know that this is not the best way to write this function, and I can use regular expressions.)

This is the code:

public String retString(String x) 
{
    int j=0;
    int i=0;
    StringBuffer y = new StringBuffer(x);

try
{


    while ( y.charAt(i) != '\0' )
    {
        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.setCharAt(j,'\0');



}
finally 
{

    System.out.println("lalalalololo " );
}

    return y.toString();


}
+1
source share
5 answers

Do you translate this code from another language? You scroll through the string until you reach the null character ( "\0"), but Java traditionally does not use them in strings. In C, this will work, but in your case you should try

i < y.length()

instead

y.charAt(i) != '\0'

Moreover,

 y.setCharAt(j,'\0')

, , .

y.setLength(j)
+4

IndexOutOfBoundsException, StringIndexOutOfBoundsException ( IndexOutOfBoundsException). , . , C/++ ( ), Java , . String (, ) .

Java String. , , . , - , .

+3

Java . String.length(), , .

+2

, C/++, java;)

.charAt(), null, StringIndexOutOfBoundsException. for, 0 y.length() - 1.

+1

( ) return y.replaceAll("\\s+"," "); ( )

and StringBuffer.length()- constant time (without slow semantics of output completion in java)

and similarly x.charAt(x.length());also produces StringIndexOutOfBoundsException(and does not return \0, as you would expect in C)

for 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 (without too much synchronization)

+1
source

Source: https://habr.com/ru/post/1622569/


All Articles