Java Program to divide a string in 'N' equal parts.

Java Program to divide a string in 'N' equal parts.

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.

Example:

Input:  str = "javajavajava";
Output: 3 equal parts of given string are 
        java java java

Approach

Java


public class DivideStringInNParts {
    public static void main(String[] args) {
        String str = "javajavajava";
        int len = str.length();
        int n = 3;
        int temp = 0, chars = len / n;
        // Stores the array of string
        String[] equalStr = new String[n];
        // Check whether a string can be divided into n equal parts
        if (len % n != 0) {
            System.out.println("Sorry length not devisable with given number");
        } else {
            for (int i = 0; i < len; i = i + chars) {
                String part = str.substring(i, i + chars);
                equalStr[temp] = part;
                temp++;
            }
            System.out.println(n + " equal parts of given string are ");
            for (int i = 0; i < equalStr.length; i++) {
                System.out.println(equalStr[i]);
            }
        }
    }
}


No comments:

Post a Comment