开发者

Splitting a string into n-length chunks in Java [duplicate]

开发者 https://www.devze.com 2023-01-23 06:41 出处:网络
This question already has answers here: 开发者_如何学C Closed 12 years ago. Possible Duplicate: Split string to equal length substrings in Java
This question already has answers here: 开发者_如何学C Closed 12 years ago.

Possible Duplicate:

Split string to equal length substrings in Java

Given the following utility method I have:

/**
 * Splits string <tt>s</tt> into chunks of size <tt>chunkSize</tt>
 *
 * @param s the string to split; must not be null
 * @param chunkSize number of chars in each chuck; must be greater than 0
 * @return The original string in chunks
 */
public static List<String> splitInChunks(String s, int chunkSize) {
    Preconditions.checkArgument(chunkSize > 0);
    List<String> result = Lists.newArrayList();
    int length = s.length();
    for (int i = 0; i < length; i += chunkSize) {
        result.add(s.substring(i, Math.min(length, i + chunkSize)));
    }
    return result;
}

1) Is there an equivalent method in any common Java library (such as Apache Commons, Google Guava) so I could throw it away from my codebase? Couldn't find with a quick look. Whether it returns an array or a List of Strings doesn't really matter.

(Obviously I wouldn't add dependency to some huge framework just for this, but feel free to mention any common lib; maybe I use it already.)

2) If not, is there some simpler and cleaner way to do this in Java? Or a way that is strikingly more performant? (If you suggest a regex-based solution, please also consider cleanness in the sense of readability for non regex experts... :-)

Edit: this qualifies as a duplicate of the question "Split string to equal length substrings in Java" because of this Guava solution which perfectly answers my question!


You can do this with Guava's Splitter:

 Splitter.fixedLength(chunkSize).split(s)

...which returns an Iterable<String>.

Some more examples in this answer.


Mostly a duplicate of Split Java String in chunks of 1024 bytes where the idea of turning it into a stream and reading N bytes at a time would seem to meet your need?

Here is a way of doing it with regex (which seems a bit of a sledgehammer for this particular nut)

0

精彩评论

暂无评论...
验证码 换一张
取 消