以下方法采用三个参数。第一个是您要修改的文本。第二个参数是您要每 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 个字符的集合;)