Java - “字符串索引超出范围”例外 [英] Java - "String index out of range" exception
问题描述
我只为练习编写了这个小函数,但抛出异常(String index out of range:29)并且我不知道为什么......
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 way to write this function and can I use regular expressions.)
这是代码:
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中,这可行,但在你的情况下你应该尝试
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()
而不是
y.charAt(i) != '\0'
< hr>
此外,
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)
这篇关于Java - “字符串索引超出范围”例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!