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.
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.
Leave a Reply
Related posts