Java - “String index out of range” exception

前端 未结 5 1946
再見小時候
再見小時候 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:11

    Are you translating this code from another language? You are looping through the string until you reach a null character ("\0"), but Java doesn't conventionally use these in strings. In C, this would work, but in your case you should try

    i < y.length()
    

    instead of

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

    Additionally, the

     y.setCharAt(j,'\0')
    

    at the end of your code will not resize the string, if that is what you are expecting. You should instead try

    y.setLength(j)
    

提交回复
热议问题