Split string to equal length substrings in Java

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

    public String[] splitInParts(String s, int partLength)
    {
        int len = s.length();
    
        // Number of parts
        int nparts = (len + partLength - 1) / partLength;
        String parts[] = new String[nparts];
    
        // Break into parts
        int offset= 0;
        int i = 0;
        while (i < nparts)
        {
            parts[i] = s.substring(offset, Math.min(offset + partLength, len));
            offset += partLength;
            i++;
        }
    
        return parts;
    }
    

提交回复
热议问题