java有效索引范围,Java - “字符串索引超出范围”例外

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.)

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

}

解决方案

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值