Java: Split String into Equal Length Substrings

If you need to split a String into equal length substrings in Java, you can use the substring() method in a loop. First, you need to calculate the length of the String and the desired length of the substrings. Then, you can use a loop to iterate over the String and use substring() to extract each substring of the desired length.

Índice
  1. Example code:

Example code:


String str = "HelloWorld";
int len = str.length();
int subLen = 3;

for (int i = 0; i < len; i += subLen) {
    String sub = str.substring(i, Math.min(len, i + subLen));
    System.out.println(sub);
}

In this example, the String "HelloWorld" is split into substrings of length 3. The loop starts at index 0 and extracts the substring "Hel". Then, it moves to index 3 and extracts the substring "loW". Finally, it moves to index 6 and extracts the substring "orl". The loop terminates when the end of the String is reached.

By using the substring() method in a loop, you can easily split a String into equal length substrings in Java.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information