在Java迭代,我可以重複上一個StringBuilder的內容和刪除/插入/替換字符使得環路將保持一致?如果是這樣,最好的做法是,我應該使用for循環,迭代器,還是從零到length() - 1的傳統循環?例如,修改一個StringBuilder,而在它
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,但這不是重點。
如果你想刪除任何東西,最好從字符串的結尾迭代到開始。 – STaefi
爲什麼你有'b.insert(2,「two」)'?它應該是'我'還是'2'? – Karthik
謝謝,修復!這是我當然! – legrass