In JavaScript this is how we can split a string at every 3-rd character
"foobarspam".match(/.{1,3}/g)
I am trying to figure out how to do this in Java. Any pointers?
In JavaScript this is how we can split a string at every 3-rd character
"foobarspam".match(/.{1,3}/g)
I am trying to figure out how to do this in Java. Any pointers?
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
for (String part : getParts("foobarspam", 3)) {
System.out.println(part);
}
}
private static List<String> getParts(String string, int partitionSize) {
List<String> parts = new ArrayList<String>();
int len = string.length();
for (int i=0; i<len; i+=partitionSize)
{
parts.add(string.substring(i, Math.min(len, i + partitionSize)));
}
return parts;
}
}
You could do it like this:
String s = "1234567890";
System.out.println(java.util.Arrays.toString(s.split("(?<=\\G...)")));
which produces:
[123, 456, 789, 0]
The regex (?<=\G...)
matches an empty string that has the last match (\G
) followed by three characters (...
) before it ((?<= )
)
Java does not provide very full-featured splitting utilities, so the Guava libraries do:
Iterable<String> pieces = Splitter.fixedLength(3).split(string);
Check out the javadoc for Splitter; it's very powerful.