Split string to equal length substrings in Java

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

    Well, it's fairly easy to do this with simple arithmetic and string operations:

    public static List splitEqually(String text, int size) {
        // Give the list the right capacity to start with. You could use an array
        // instead if you wanted.
        List ret = new ArrayList((text.length() + size - 1) / size);
    
        for (int start = 0; start < text.length(); start += size) {
            ret.add(text.substring(start, Math.min(text.length(), start + size)));
        }
        return ret;
    }
    

    I don't think it's really worth using a regex for this.

    EDIT: My reasoning for not using a regex:

    • This doesn't use any of the real pattern matching of regexes. It's just counting.
    • I suspect the above will be more efficient, although in most cases it won't matter
    • If you need to use variable sizes in different places, you've either got repetition or a helper function to build the regex itself based on a parameter - ick.
    • The regex provided in another answer firstly didn't compile (invalid escaping), and then didn't work. My code worked first time. That's more a testament to the usability of regexes vs plain code, IMO.

提交回复
热议问题