This post will discuss how to split a string into fixed-length chunks in Java where the last chunk can be smaller than the specified length.

1. Using Guava

If you prefer the Guava library, you can use the Splitter class. For example, the expression Splitter.fixedLength(n).split(s) returns a splitter that divides the string s into chunks of length n.

Download Code

2. Using String.split() method

The String class contains the split() method that splits a string around matches of the given regular expression. You can use it to split a string into equal size chinks. The following code uses the split() method to split a string into equal size chunks of length 5 using the regular expression (?<=\\G.{5}) that uses lookbehind.

Download  Run Code

3. Using String.substring() method

The idea is to extract each chunk using the String.substring(int, int) method to partition the string into fixed-length slices.

Download  Run Code

 
If you use Java 8 or above, you can use Stream API. Here's the equivalent code:

Download  Run Code

4. Using Pattern.compile() method

To split a string into fixed-length chunks, you can create a matcher to determine the indexes of the chunk. Here's how the code would look like:

Download  Run Code

That's all about splitting a string into fixed-length chunks in Java.