从右边开始,在 Java 字符串中每 8 个字符之后插入一个(破折号/减号字符)的最佳方法是什么?-
例子:
1111 -> 1111
111111111 -> 1-11111111
1111111111111111 -> 11111111-11111111
100001111111111111111 -> 10000-11111111-11111111
我的尝试,以表明我已经尝试过自己做(下面的评论问:“这是作业吗?”:
import junit.framework.TestCase;
public class InsertCharacterAfterEveryNCharacters extends TestCase {
public static String insertSpacerAfterNCharactersFromTheRight(char spacer,
int spacing, String string) {
final int length = string.length();
final int newStringCapacity = length + (int) Math.ceil(length / (double) spacing);
StringBuilder stringBuilder = new StringBuilder(newStringCapacity);
for (int i = length - 1; i >= 0; i--) {
stringBuilder.append(string.charAt(i));
if (i % spacing == 0 && i > 0) {
stringBuilder.append(spacer);
}
}
return stringBuilder.toString();
}
public static void testInsertSpacerAfterNCharactersFromTheRight() {
assertEquals("", insertSpacerAfterNCharactersFromTheRight('-', 8, ""));
assertEquals("1", insertSpacerAfterNCharactersFromTheRight('-', 8, "1"));
assertEquals("11", insertSpacerAfterNCharactersFromTheRight('-', 8, "11"));
assertEquals("11111111",
insertSpacerAfterNCharactersFromTheRight('-', 8, "11111111"));
assertEquals("1-11111111",
insertSpacerAfterNCharactersFromTheRight('-', 8, "111111111"));
assertEquals("11111111-11111111",
insertSpacerAfterNCharactersFromTheRight('-', 8, "1111111111111111"));
}
}