Monday, August 13, 2012

Split String to equal length substrings in Java

Solution1: Use of Regular Expressions
System.out.println(Arrays.toString(
    "abcdefghij".split("(?<=\\G.{4})")
));

Output1:
[abcd, efgh, ij]

Solution2: Use of simple for Loop
String text = "abcdefghij";
 int size = 4;

        for (int start = 0; start < text.length(); start += size) {
            System.out.println( text.substring(start, Math.min(text.length(), start + size)));
        }

Output2:
abcd
efgh
ij

Solution3: Use of Splitter class(Guava from Google)
for(final String token :
    Splitter.fixedLength(4).split("abcdefghij")){
    System.out.println(token);
}