This post will discuss how to split a string into substrings of equal size in Java.

To split a string into substrings of equal size in Java, we can use one of the following methods:

1. Using String.split() method

We can write a regular expression that matches the position where the previous match ended, and use it to split the string into substrings of a given size with String.split() method. For example, we can use the following code to split the string Thequickbrownfoxjumpsoverthelazydog into substrings of size 3: [The, qui, ckb, row, nfo, xju, mps, ove, rth, ela, zyd, og].

Download  Run Code

 
Here, \G require the match to occur only at the end of the previous match. If there was no previous match, it matches the beginning of the string. The enclosing positive lookbehind (?<=text) matches the specified characters from the end of the last match. The split() method will return an array of strings that are separated by this position.

2. Using String.substring() method

Regex is not recommended and should be avoided if possible. We can use a simple loop and the substring() method of the String class to break the string into substrings of the given size. The substring() method takes two parameters: the starting index and the ending index of the substring. For example, the following code to split a string into a list of substrings of size 3. If an array is needed instead of a list, we can convert list into an array.

Download  Run Code

3. Using Guava’s Splitter Class

Another good alternative is to use the Splitter class from the Guava library to split the string into substrings of a fixed length. It returns an Iterable instead of an array, which we can convert into a list using the Lists.newArrayList() method. It creates a mutable ArrayList instance containing all elements of the Iterable. For example, the following code to split a string into a list of substrings of size 3:

Download Code

 
If an array is needed instead of a list, we can call Iterables.toArray() method in place of Lists.newArrayList(). Here is a sample code that demonstrates its usage:

Download Code

That’s all about splitting a string into two equal-length substrings in Java.