How to split a string array into small chunk arrays in java?

前端 未结 12 1941
春和景丽
春和景丽 2020-12-05 05:15

Below is the example of the code snippet which needs the help

Example:

[1,2,3,4,5]
  • if the chunk size is 1,
12条回答
  •  粉色の甜心
    2020-12-05 05:34

    This should do the trick

    public static List split(String string, int chunk) {
        Pattern pattern = Pattern.compile("(([0-9]+,){" + (chunk - 1)
                + "}[0-9]+)|[0-9]+");
        Matcher matcher = pattern.matcher(string);
    
        List result = new ArrayList();
        while (matcher.find())
            result.add("[" + matcher.group() + "]");
    
        return result;
    }
    

    Test code:

    for (int chunkSize = 1; chunkSize < 6; ++chunkSize) {
        System.out.println("test for chunk size: " + chunkSize);
        for (String string : split("[1,2,3,4,5]", chunkSize))
            System.out.format("\t%s\n", string);
    }
    

    Output:

    test for chunk size: 1
        [1]
        [2]
        [3]
        [4]
        [5]
    test for chunk size: 2
        [1,2]
        [3,4]
        [5]
    test for chunk size: 3
        [1,2,3]
        [4]
        [5]
    test for chunk size: 4
        [1,2,3,4]
        [5]
    test for chunk size: 5
        [1,2,3,4,5]
    

提交回复
热议问题