Open In App

How to Split a String into Equal Length Substrings in Java?

Last Updated : 29 Nov, 2024
Comments
Improve
Suggest changes
5 Likes
Like
Report

In Java, splitting a string into smaller substrings of equal length is useful for processing large strings in manageable pieces. We can do this with the substring method of the loop. This method extracts a substring of the specified length from the input string and stores it in a list.

Example:

In the below example, we will use a for loop and the substring() method to split a string into substrings of equal length.


Output
Hello
, Gee
ks

Explanation: In the above example, the string "Hello, Geeks" is split into substrings of length 5. Then the substring() method is used inside the loop to extract substrings. The Math.min() method ensures that the substring does not exceed the original string's length.

Java Programs to Split a String into Equal Length Substrings

1. Split a String into Substrings of Length 4


Output
Geek
sfor
Geek
s

Explanation: In the above example, the string "GeeksforGeeks" is split into substrings of length 4.

2. Using a Custom Method to Split the String

We can create a custom method to split a string into substrings of equal length without relying on external libraries. This method involves iterating through the original string and extracting substrings of the desired length. This is a more structured approach.


Output
Geeks
forGe
eks

Explanation: In the above example, the splitString() method divides the string into substrings of equal length. The


Next Article

Similar Reads