下面的方法采用三个参数。第一个是你想要修改的文本。第二个参数是要插入每n个字符的文本。第三个是你想插入文本的时间间隔。
private String insertEveryNCharacters(String originalText, String textToInsert, int breakInterval) {
String withBreaks = "";
int textLength = originalText.length(); //initialize this here or in the start of the for in order to evaluate this once, not every loop
for (int i = breakInterval , current = 0; i <= textLength || current < textLength; current = i, i += breakInterval) {
if(current != 0) { //do not insert the text on the first loop
withBreaks += textToInsert;
}
if(i <= textLength) { //double check that text is at least long enough to go to index i without out of bounds exception
withBreaks += originalText.substring(current, i);
} else { //text left is not longer than the break interval, so go simply from current to end.
withBreaks += originalText.substring(current); //current to end (if text is not perfectly divisible by interval, it will still get included)
}
}
return withBreaks;
}
你会调用这个方法是这样的:
String splitText = insertEveryNCharacters("this is my string which I need to modify...I love stackoverlow:)", "<br>", 10);
结果是:
this is my<br> string wh<br>ich I need<br> to modify<br>...I love <br>stackoverl<br>ow:)
^这是不同于你的榜样的结果,因为你有一组与9个字符而不是10,因为人为错误;)
太棒了!如果我不想把
放在文字中,怎么样?for例如避免这样的事情:stackover
流和直接放
在单词的结尾? – Giancarlo 2009-02-11 15:09:30
然后这是一个非常困难的问题。正则表达式*可能是最好的方式,但是您需要先确定需求。 – 2009-02-11 15:14:34