在Java中,我可以迭代StringBuilder的内容并删除/插入/替换字符,以使循环保持一致吗?如果是这样,最佳实践,我应该使用从零到长度() - 1的for循环,迭代器或传统循环吗?例如,
StringBuilder b=new StringBuilder("12345");
for (int i=0; i< b.length(); i++) //traditional loop, iterator(which?),other?
char c= b.chartAt(i);
if(c == '1') b.deleteCharAt(i); // reduce the size,what is i pointing to now?
if(c=='2') b.insert(i,"two"); //increase the size
}
编辑:说我有一个大字符串,我需要对其进行更改,我不想每次都制作副本。 StringBuilder是一个可变字符串,如何正确使用它来进行内部更改?我知道我可以在String本身上使用replace / replaceall,但这不是重点。
答案 0 :(得分:1)
我认为你可以做到这一点。我同意STaefi,你应该从最后开始迭代:
StringBuilder b=new StringBuilder("12345");
for (int i = b.length() - 1; i >=0 ; i--){ //traditional loop, iterator(which?),other?
char c = b.charAt(i);
if(c == '1') b.deleteCharAt(i); // reduce the size,what is i pointing to now?
if(c=='2') b.insert(2,"two"); //increase the size
}
答案 1 :(得分:0)
您可以这样做,但您应该相应地更改i
的值。
StringBuilder b=new StringBuilder("12345");
for (int i=0; i< b.length(); i++) {
char c= b.chartAt(i);
if(c == '1'){
b.deleteCharAt(i);
i--; // because you don't want to miss out the next char after deleting the present char
}
else if(c=='2'){
b.insert(i,"two"); // I am not sure you want 2 or i
i=i+2; // change this accordingly.
}
}