Split string to equal length substrings in Java

后端 未结 21 1862
日久生厌
日久生厌 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:24

    @Test
    public void regexSplit() {
        String source = "Thequickbrownfoxjumps";
        // define matcher, any char, min length 1, max length 4
        Matcher matcher = Pattern.compile(".{1,4}").matcher(source);
        List result = new ArrayList<>();
        while (matcher.find()) {
            result.add(source.substring(matcher.start(), matcher.end()));
        }
        String[] expected = {"Theq", "uick", "brow", "nfox", "jump", "s"};
        assertArrayEquals(result.toArray(), expected);
    }
    

提交回复
热议问题