In this article, we will write a java program to divide a string in ‘n’ equal parts. There are few things which we need to check before we divide the given string in equal parts. First thing we can check is to divide the number of characters in the string by the ‘n’, if the remainder is zero then this string can be divided in ‘n’ equal parts else it cannot be divided in equal parts.
Program to divide a given String in ‘n’ equal parts
Steps followed in the following program are:
- Find the number of characters in the string using length() method and divide it by n, if the remainder is not equal to 0 then print String cannot be divided else proceed to next step.
- Use the substring() method to divide the given string in ‘n’ equal parts and store the strings in a String array.
- Print the String array that contains the substrings of the given string.
public class JavaExample {
public static void main(String[] args) {
String str = "TextOneTextTwo";
//Finds the length of the given string
int len = str.length();
//n represents the number of equal parts. Here 2
//means the given string will be divided in two equal parts
int n = 2;
//numberOfChar represents the number of chars in divided strings
int temp = 0, numberOfChar = len/n;
String[] strParts = new String [n];
//Checking whether the string can be divided in equal parts or not
if(len % n != 0) {
System.out.println("String cannot be divided into "+ n +" equal parts.");
}
else {
for(int i = 0; i < len; i = i+numberOfChar) {
//Dividing string using substring() method
String subStr = str.substring(i, i+numberOfChar);
strParts[temp] = subStr;
temp++;
}
System.out.println(n + " equal parts of the given String are: ");
for(int i = 0; i < strParts.length; i++) {
System.out.println(strParts[i]);
}
}
}
}
Output:
Leave a Reply