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:
Result
In case you want to split the string equally backwards, i.e. from right to left, for example, to split
1010001111
to[10, 1000, 1111]
, here's the code:Here's the regex one-liner version:
\G
is a zero-width assertion that matches the position where the previous match ended. If there was no previous match, it matches the beginning of the input, the same as\A
. The enclosing lookbehind matches the position that's four characters along from the end of the last match.Both lookbehind and
\G
are advanced regex features, not supported by all flavors. Furthermore,\G
is not implemented consistently across the flavors that do support it. This trick will work (for example) in Java, Perl, .NET and JGSoft, but not in PHP (PCRE), Ruby 1.9+ or TextMate (both Oniguruma). JavaScript's/y
(sticky flag) isn't as flexible as\G
, and couldn't be used this way even if JS did support lookbehind.I should mention that I don't necessarily recommend this solution if you have other options. The non-regex solutions in the other answers may be longer, but they're also self-documenting; this one's just about the opposite of that. ;)
Also, this doesn't work in Android, which doesn't support the use of
\G
in lookbehinds.If you're using Google's guava general-purpose libraries (and quite honestly, any new Java project probably should be), this is insanely trivial with the Splitter class:
and that's it. Easy as!
Another brute force solution could be,
Where the code just steps through the string with substrings