Split string to equal length substrings in Java

后端 未结 21 1827
日久生厌
日久生厌 2020-11-22 02:56

How to split the string \"Thequickbrownfoxjumps\" to substrings of equal size in Java. Eg. \"Thequickbrownfoxjumps\" of 4 equal size should give th

21条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 03:32

    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());
    }
    

提交回复
热议问题