Split a String Every n Characters in Java
Split a String Every n Characters in Java
If you have a string that is too long and need to split it into smaller strings, Java provides a perfect way to accomplish this task. The function that can be used for the same is substring(). This function will help you break down a given string into multiple strings of length n characters.
To use this function first declare and initialize a string variable. In this example we will use the string “splitEveryNCharacter”.
String str = "splitEveryNCharacter";
Now in order to split this string into substring of length 5 (you can replace the value with any number) you will be using the following syntax.
for (int i = 0; i < str.length(); i+=5)
{
System.out.print(str.substring(i, Math.min(str.length(), i + 5)));
}
In the above syntax, You are essentially using a loop to iterate through each character every 5. The substring() function takes in two parameters: start index and end index. Hence as you iterate through each loop the start=i and end=Math.min(str.length(), i + 5). This will make sure that we don’t exceed the length of the string. At the end of the last iteration, the variable ‘i’ i.e. the start will be at the length of the string and the min function will avoid exceeding the length of the string.
The output of the above code will look like below.
spli
tEve
ryNC
harac
ter