Divide a string in N equal parts in Java

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 characters, If the characters comes out to be a floating point value, we cannot divide the string otherwise run for loop to traverse the string and divide the string at every chars interval.

ALGORITHM

  • STEP 1: start
  • STEP 2: define str = “aaaabbbbcccc”
  • STEP 3: define len
  • STEP 4: set n =3
  • STEP 5: set  temp = 0.
  • STEP 6: chars = len/n
  • STEP 7: define String[] equal str.
  • STEP 8: IF (len %n!=0)
    then PRINT (“String can’t be divided into equal parts”)
    else go to step 9
  • STEP 9: SET i =0.
  • STEP 10: repeat step 11 to step 14 until  i<len
  • STEP 11: define substring part.
  • STEP 12: equalstr [temp] = part
  • STEP 13: temp = temp + 1
  • STEP 14: i = i + chars
  • STEP 15: print n
  • STEP 16: SET i=0. repeat step 18 and 19 until  i<equalstr.length
  • STEP 17: print equalstr[i]
  • STEP 18: i = i + 1
  • STEP 19: End
    public class DivideString {  
        public static void main(String[] args) {  
              String str = "aaaabbbbcccc"; 
            int len = str.length();  
            int n = 3;  
            int temp = 0, chars = len/n;    
            String[] equalStr = new String [n];    
            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(n + " equal parts of given string are ");  
                for(int i = 0; i < equalStr.length; i++) {  
                    System.out.println(equalStr[i]);  
                    }  
                }  
            }  
    }

    OUTPUT

    3 equal parts of given string are
    aaaa
    bbbb
    cccc

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top