我试图将 for 循环插入到 Stringbuilder 但它崩溃了。这是我的代码
StringBuilder sb = new StringBuilder("This is a text");
for(int i = 0;i < sb.length();i++){
if(sb.charAt(i) == 't'){
sb.insert(i, 't');
}
}
这样做的目的是将每个“t”加倍。
最佳答案
您将收到 OutOfMemoryError
,因为您没有跳过要加倍的 t
字符。
This is a text
^
This is a ttext
^
This is a tttext
^
这会一直持续到内存耗尽为止。
您必须在插入双倍 t
后通过递增 i
来跳过刚刚添加的 t
。
if (sb.charAt(i) == 't')
{
sb.insert(i, 't');
i++;
}
关于java - 插入for循环失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33813659/