Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

split

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!

like image 287
Jonik Avatar asked Nov 04 '10 14:11

Jonik


People also ask

How can I split a string into segments of N characters in Java?

Using the String#split Method As the name implies, it splits a string into multiple parts based on a given delimiter or regular expression. As we can see, we used the regex (? <=\\G. {” + n + “}) where n is the number of characters.

How do I split a string into multiple parts?

Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.


2 Answers

You can do this with Guava's Splitter:

 Splitter.fixedLength(chunkSize).split(s)

...which returns an Iterable<String>.

Some more examples in this answer.

like image 128
Sean Patrick Floyd Avatar answered Oct 06 '22 09:10

Sean Patrick Floyd


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)

like image 25
The Archetypal Paul Avatar answered Oct 06 '22 09:10

The Archetypal Paul