Split string to equal length substrings in Java

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

    In case you want to split the string equally backwards, i.e. from right to left, for example, to split 1010001111 to [10, 1000, 1111], here's the code:

    /**
     * @param s         the string to be split
     * @param subLen    length of the equal-length substrings.
     * @param backwards true if the splitting is from right to left, false otherwise
     * @return an array of equal-length substrings
     * @throws ArithmeticException: / by zero when subLen == 0
     */
    public static String[] split(String s, int subLen, boolean backwards) {
        assert s != null;
        int groups = s.length() % subLen == 0 ? s.length() / subLen : s.length() / subLen + 1;
        String[] strs = new String[groups];
        if (backwards) {
            for (int i = 0; i < groups; i++) {
                int beginIndex = s.length() - subLen * (i + 1);
                int endIndex = beginIndex + subLen;
                if (beginIndex < 0)
                    beginIndex = 0;
                strs[groups - i - 1] = s.substring(beginIndex, endIndex);
            }
        } else {
            for (int i = 0; i < groups; i++) {
                int beginIndex = subLen * i;
                int endIndex = beginIndex + subLen;
                if (endIndex > s.length())
                    endIndex = s.length();
                strs[i] = s.substring(beginIndex, endIndex);
            }
        }
        return strs;
    }
    

提交回复
热议问题