Java Program to divide a string in 'N' equal parts.
Here, our task is to divide the string S into n equal parts. We will print an error message if the string cannot be divisible into n equal parts otherwise all the parts need to be printed as the output of the program.
To check whether the string can be divided into N equal parts, we need to divide the length of the string by n and assign the result to variable chars.
If the char comes out to be a floating point value, we can't divide the string otherwise run for loop to traverse the string and divide the string at every chars interval.
string 1
"aaaabbbbcccc"
Class
Program
class N_divide {
public static void main(String[] args) {
//declare array
String str1="Brag";
int len = str.length();
int n=3, temp=0, chars=len/n
String[] equalStr = new String [n];
//Check whether a string can be divided into n equal parts
if (len % n != 0) {
System.out.println("Sorry this string cannot be divided into " + n + " equal parts." ); }
else {
for(int i = 0; i < len; i = i+chars) {
String part = str.substring(i, i+chars);
equalStr[temp] = part;
temp++;
}
}
System.out.println(" equal parts of given string are " + n);
for(int int i = 0; i < equalStr.length; i++) {
System.out.println(equalStr[i]);
}
}
}
output
3 equal parts of given string are
aaaa
bbbb
cccc
Theory