How to split the string \"Thequickbrownfoxjumps\"
to substrings of equal size in Java.
Eg. \"Thequickbrownfoxjumps\"
of 4 equal size should give th
Here is my version based on RegEx and Java 8 streams. It's worth to mention that Matcher.results()
method is available since Java 9.
Test included.
public static List splitString(String input, int splitSize) {
Matcher matcher = Pattern.compile("(?:(.{" + splitSize + "}))+?").matcher(input);
return matcher.results().map(MatchResult::group).collect(Collectors.toList());
}
@Test
public void shouldSplitStringToEqualLengthParts() {
String anyValidString = "Split me equally!";
String[] expectedTokens2 = {"Sp", "li", "t ", "me", " e", "qu", "al", "ly"};
String[] expectedTokens3 = {"Spl", "it ", "me ", "equ", "all"};
Assert.assertArrayEquals(expectedTokens2, splitString(anyValidString, 2).toArray());
Assert.assertArrayEquals(expectedTokens3, splitString(anyValidString, 3).toArray());
}