How to split the string "Thequickbrownfoxjumps"
to substrings of equal size in Java.
Eg. "Thequickbrownfoxjumps"
of 4 equal size should give the output.
["Theq","uick","brow","nfox","jump","s"]
Similar Question:
How to split the string "Thequickbrownfoxjumps"
to substrings of equal size in Java.
Eg. "Thequickbrownfoxjumps"
of 4 equal size should give the output.
["Theq","uick","brow","nfox","jump","s"]
Similar Question:
Here is my version based on RegEx and Java 8 streams. It's worth to mention that
Matcher.results()
method is available since Java 9.Test included.
This is very easy with Google Guava:
Output:
Or if you need the result as an array, you can use this code:
Reference:
Splitter.fixedLength()
Splitter.split()
Iterables.toArray()
Note: Splitter construction is shown inline above, but since Splitters are immutable and reusable, it's a good practice to store them in constants:
Here is a one liner implementation using Java8 streams:
It gives the following output:
I asked @Alan Moore in a comment to the accepted solution how strings with newlines could be handled. He suggested using DOTALL.
Using his suggestion I created a small sample of how that works:
But I like @Jon Skeets solution in https://stackoverflow.com/a/3760193/1237974 also. For maintainability in larger projects where not everyone are equally experienced in Regular expressions I would probably use Jons solution.
I'd rather this simple solution: