Java: How to split a string by a number of characters?

前端 未结 11 1485
夕颜
夕颜 2020-11-27 06:59

I tried to search online to solve this question but I didn\'t found anything.

I wrote the following abstract code to explain what I\'m asking:

String         


        
11条回答
  •  不知归路
    2020-11-27 07:21

    Quick Hack

    private String[] splitByNumber(String s, int size) {
        if(s == null || size <= 0)
            return null;
        int chunks = s.length() / size + ((s.length() % size > 0) ? 1 : 0);
        String[] arr = new String[chunks];
        for(int i = 0, j = 0, l = s.length(); i < l; i += size, j++)
            arr[j] = s.substring(i, Math.min(l, i + size));
        return arr;
    }
    

提交回复
热议问题