Splitting a string at every n-th character
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.
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;
}
}
As an addition to Bart Kiers answer I want to add that it is possible instead of using the three dots ...
in the regex expression which are representing three characters you can write .{3}
which has the same meaning.
Then the code would look like the following:
String bitstream = "00101010001001010100101010100101010101001010100001010101010010101";
System.out.println(java.util.Arrays.toString(bitstream.split("(?<=\\G.{3})")));
With this it would be easier to modify the string length and the creation of a function is now reasonable with a variable input string length. This could be done look like the following:
public static String[] splitAfterNChars(String input, int splitLen){
return input.split(String.format("(?<=\\G.{%1$d})", splitLen));
}
An example in IdeOne: http://ideone.com/rNlTj5
Late Entry.
Following is a succinct implementation using Java8 streams, a one liner:
String foobarspam = "foobarspam";
AtomicInteger splitCounter = new AtomicInteger(0);
Collection<String> splittedStrings = foobarspam
.chars()
.mapToObj(_char -> String.valueOf((char)_char))
.collect(Collectors.groupingBy(stringChar -> splitCounter.getAndIncrement() / 3
,Collectors.joining()))
.values();
Output:
[foo, bar, spa, m]