Java String Handling RegEx

Java split String in equal length substrings example

Java split String in equal length substrings example shows how to split string in equal length substrings in Java. Example also shows various approaches to split string in equal length substrings.

How to split string in equal length substrings in Java?

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

1) Split string in equal substrings using Math and String classes

For this approach, we are going to use only String and Math classes 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 required substring length. 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) Split string in equal substrings using regular expression

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

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

Output

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

 

Tags
Join 1000+ fellow learners! Enter your email address below: