title: Java string, insert a dash after every 8 characters, starting from the right
body: <p>What's the <strong>best</strong> way to insert a <code>-</code> (dash/minus character) after every 8 characters in a Java String, starting from the right?</p>
  
  <p>Examples:</p>
  
  <pre><code>1111 -&gt; 1111
  111111111 -&gt; 1-11111111
  1111111111111111 -&gt; 11111111-11111111
  100001111111111111111 -&gt; 10000-11111111-11111111
  </code></pre>
  
  <p>My attempt, to show that I have tried doing it myself (a comment below asks: "is this homework?":</p>
  
  <pre><code>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 &gt;= 0; i--) {
        stringBuilder.append(string.charAt(i));
        if (i % spacing == 0 &amp;&amp; i &gt; 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"));
    }
  }
  </code></pre>