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!
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.
Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With