Java – “字符串索引超出范围”exception

我只为练习编写了这个小函数,但抛出exception(“String index out of range:29”),我不知道为什么……

(我知道这不是编写此函数的最佳方法,我可以使用正则表达式。)

这是代码:

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

您是否正在使用其他语言翻译此代码? 您循环遍历字符串,直到到达空字符( "\0" ),但Java通常不会在字符串中使用这些字符。 在C中,这可行,但在你的情况下,你应该尝试

 i < y.length() 

代替

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

另外,

  y.setCharAt(j,'\0') 

在你的代码的末尾不会调整字符串的大小,如果这是你期望的。 你应该试试

 y.setLength(j) 

此exception是IndexOutOfBoundsException,但更具体地说,是StringIndexOutOfBoundsException (从IndexOutOfBoundsException派生)。 收到此类错误的原因是因为您超出了可索引集合的范围。 这是C / C ++不能做的事情(你手动检查集合的边界),而Java将这些内置到它们的集合中以避免诸如此类的问题。 在这种情况下,您使用String对象就像一个数组(可能是它在实现中的那个)并越过String的边界。

Java不会在String的公共接口中公开null终止符。 换句话说,您无法通过搜索null终止符来确定String的结尾。 相反,理想的方法是确保不超过字符串的长度。

Java字符串不以空值终止。 使用String.length()来确定停止的位置。

看起来你是一个C / C ++程序员来到java;)

一旦你使用.charAt()超出范围,它就不会达到null,它会达到StringIndexOutOfBoundsException。 所以在这种情况下,你需要一个从0到y.length() – 1的for循环。

更好的实现(使用正则表达式)只需return y.replaceAll("\\s+"," "); (这甚至取代了其他空白)

StringBuffer.length()是常量时间(在java中没有慢速空终止语义)

x.charAt(x.length());类似x.charAt(x.length()); 还会抛出一个StringIndexOutOfBoundsException (而不是像C中你期望的那样返回\0

对于固定代码:

 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 

顺便说一句StringBuilder是一个更快的实现(没有不必要的同步)