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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package com.javacodeexamples.stringexamples; import java.util.Arrays; public class SplitStringEqualSubstringsExample { public static void main(String[] args) { String str = "abcdefghijk"; //required substring length int substringSize = 2; /* * calculate how many total substrings * will be created */ int totalSubstrings = (int) Math.ceil( (double)str.length()/substringSize ); //use ArrayList or String array String[] strSubstrings = new String[totalSubstrings]; int index = 0; for(int i=0; i < str.length(); i = i + substringSize){ strSubstrings[index++] = str.substring(i, Math.min(i + substringSize, str.length())); } //print substrings System.out.println(Arrays.toString(strSubstrings)); } } |
Output
1 |
[ab, cd, ef, gh, ij, k] |
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.
1 2 3 4 |
(?<=) - Positive lookbehind expression \G - Boundary match . - anything {2} - 2 characters long |
\G
matches the position at the end of the last match. It matches at the start of the String for the first match.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.javacodeexamples.stringexamples; import java.util.Arrays; public class SplitStringEqualSubstringsExample { public static void main(String[] args) { String str = "abcdefghijk"; String[] strSubstrings = str.split("(?<=\\G.{2})"); System.out.println(Arrays.toString(strSubstrings)); } } |
Output
1 |
[ab, cd, ef, gh, ij, k] |
This example is a part of String in Java tutorial.
Please let me know your views in the comments section below.