Skip to content

Java split String into equal length substrings example

Java split String in equal length substrings example shows how to split the string into equal length substrings in Java using various approaches including Math class and regex.

How to split a string into equal length substrings in Java?

There are a couple of ways using which you can split string into equal substrings as given below.

1) Using the Math and String classes

For this approach, we are going to use only the String class and Java Math class as given below.

Output

We first calculated the number of substrings that will be created based on the total length of the input string and the required substring length. The next step was to create an array with that size so that it can hold that many substrings.

Once we created an array, we looped through the string until the string length and incremented the loop index by substring size. Inside the loop, we took the substring from string starting from the loop index and ending at either loop index + substring size or string length whichever is lower.

2) Using the regular expression

We can achieve the same output using regular expression as well. We are going to use the "(?<=\\G.{2})" regular expression pattern.

\G matches the position at the end of the last match. It matches at the start of the String for the first match.

Output

This example is a part of String in Java tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.