Wednesday, August 15, 2012

Insert a spacer character into a given String every n characters from the right


import junit.framework.TestCase;
/**
 * Insert a spacer character into a given String every n characters from the
 * right.
 */
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"));
  }
}

No comments:

Post a Comment