Java Program to Divide a String in ‘N’ Equal Parts
Overview
In this blog, we will learn to write a Java program that divides a string in ‘N’ equal parts when the string is user-defined.
Program Description
Input a string from the user. The task is to divide the string into ‘N’ equal parts and print all the divided strings. The program must check if it is possible to divide the string into ‘N’ equal parts. If not, display an error message and exit the program.

How It Works
Find the length of the string using the function “length()” (i.e. length = str.length()).
Check whether the string can be divided into ‘N’ equal parts. If the string can’t be divided into ‘N’ equal parts (i.e. length % N != 0), print a message and exit the program.
Else (i.e. length % N == 0), do the following:
- Declare a string array of size ‘N’ (say ‘dividedStr’).
- Calculate the size of each part by dividing the length of the string by ‘N’ (partSize = length / N);
- Loop through the input string. In the loop, extract a substring from the input string with incrementing character ‘i’ as starting index and ‘i + partSize’ as ending index. Assign the extracted substring to the array.
- Each time, the loop is incremented with a condition of ‘i += partSize’.
- During each loop execution, increment the array index.
- Now, the divided string parts are stored in the array which is printed on the screen.
Source Code
Here is the complete Java program to divide a given string into ‘N’ equal parts:
Test Cases
1.Enter the string: GuviGeek
Enter the value of ‘N’: 2
2 equal parts of the given string are:
Guvi
Geek
2.Enter the string: GuviGeek
Enter the value of ‘N’: 3
GuviGeek cannot be divided into 3 equal parts!
Are you looking to master coding and crack top company interviews? Go ahead and try GUVI’s Pro Subscription to help you with everything needed to build a strong Technical Career.
Know more about GUVI:
Also, download GUVI’s app to learn the latest IT skills in vernacular languages.