Skip to content

Instantly share code, notes, and snippets.

@marvk
Last active February 15, 2019 11:32
Show Gist options
  • Save marvk/33ab88690dbf57aae1c59306e0186063 to your computer and use it in GitHub Desktop.
Save marvk/33ab88690dbf57aae1c59306e0186063 to your computer and use it in GitHub Desktop.
Groupify
public final class Groupify {
public static String groupify(final String input, final int groupSize) {
if (groupSize < 1) {
throw new IllegalArgumentException("groupSize must be bigger than zero, was " + groupSize);
}
final String inputPadded = input + "x".repeat((groupSize - input.length() % groupSize) % groupSize);
final String[] split = inputPadded.split("(?<=\\G.{" + groupSize + "})");
return String.join(" ", split);
}
}
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class GroupifyTest {
@Test
void groupify() {
assertEquals("HI TH ER Ex", Groupify.groupify("HITHERE", 2));
assertEquals("DISC ORDx", Groupify.groupify("DISCORD", 4));
assertEquals("OHMY", Groupify.groupify("OHMY", 4));
assertEquals("test1234567xxxxxxxxx", Groupify.groupify("test1234567", 20));
assertEquals("w o w t h i s i s s u c h a l o n g s e n t e n c e . . .", Groupify.groupify("wowthisissuchalongsentence...", 1));
assertEquals("", Groupify.groupify("", 1));
assertThrows(NullPointerException.class, () -> Groupify.groupify(null, 1));
assertThrows(IllegalArgumentException.class, () -> Groupify.groupify("noo", -1));
assertThrows(IllegalArgumentException.class, () -> Groupify.groupify("yikes", 0));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment