What's the best way to insert a - (dash/minus character) after every 8 characters in a Java String, starting from the right?
Examples:
1111 -> 1111
111111111 -> 1-11111111
1111111111111111 -> 11111111-11111111
100001111111111111111 -> 10000-11111111-11111111
My attempt, to show that I have tried doing it myself (a comment below asks: "is this homework?":
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"));
  }
}
 
     
     
     
     
    