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:
You can use substring
from String.class
(handling exceptions) or from Apache lang commons (it handles exceptions for you)
static String substring(String str, int start, int end)
Put it inside a loop and you are good to go.
Well, it's fairly easy to do this by brute force:
public static List<String> splitEqually(String text, int size) {
// Give the list the right capacity to start with. You could use an array
// instead if you wanted.
List<String> ret = new ArrayList<String>((text.length() + size - 1) / size);
for (int start = 0; start < text.length(); start += size) {
ret.add(text.substring(start, Math.min(text.length(), start + size)));
}
return ret;
}
I don't think it's really worth using a regex for this.
EDIT: My reasoning for not using a regex:
public String[] splitInParts(String s, int partLength)
{
int len = s.length();
// Number of parts
int nparts = (len + partLength - 1) / partLength;
String parts[] = new String[nparts];
// Break into parts
int offset= 0;
int i = 0;
while (i < nparts)
{
parts[i] = s.substring(offset, Math.min(offset + partLength, len));
offset += partLength;
i++;
}
return parts;
}
public static String[] split(String src, int len) {
String[] result = new String[(int)Math.ceil((double)src.length()/(double)len)];
for (int i=0; i<result.length; i++)
result[i] = src.substring(i*len, Math.min(src.length(), (i+1)*len));
return result;
}
This is very easy with Google Guava:
for(final String token :
Splitter
.fixedLength(4)
.split("Thequickbrownfoxjumps")){
System.out.println(token);
}
Output:
Theq
uick
brow
nfox
jump
s
Or if you need the result as an array, you can use this code:
String[] tokens =
Iterables.toArray(
Splitter
.fixedLength(4)
.split("Thequickbrownfoxjumps"),
String.class
);
Reference:
I played with the idea to create a regex version also, but I couldn't come up with a one-liner for String.split(). And I deleted my previous attempts because the problem was now solved by Alan Moore. But I still agree with the others that regex is not the right tool for this (even though it works).
In short:
Use Guava's one-liner (most elegant imho) or Alan's one-liner (the answer you were looking for) or Jon Skeet's multiliner (probably most efficient).
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:
for (String substring : Splitter.fixedLength(4).split(inputString)) {
doSomethingWith(substring);
}
and that's it. Easy as!
Here's the regex one-liner version:
System.out.println(Arrays.toString(
"Thequickbrownfoxjumps".split("(?<=\\G.{4})")
));
\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).
EDIT: 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. ;)