Divide a String Into n Equal Parts in Java

Dividing a string into equal parts is a common task in Java programming. Whether for data processing or formatting, this guide will demonstrate how to split a string into n equal parts using Java.

Divide a String Into n Equal Parts in Java- Code

// Divide a String Into n Equal Parts in Java
import java.util.*;
public class Main 
{  
    public static void main(String[] args) 
    {  
        //Take input from the user
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the string: ");
        String str = sc.nextLine();  
        //Enter the total number of parts 
        System.out.println("Enter the value of n: ");
        int n = sc.nextInt();  
        int temp = 0, chars = str.length()/n; 
        
        //Stores the array of string  
        String[] newStr = new String [n];  
        //Check whether a string can be divided into n equal parts  
        if(str.length() % n != 0) 
        {  
            System.out.println("Invalid Input"); 
            System.out.println("String size is not divisible by "+n); 
            System.out.println("Try Again"); 
        }  
        else 
        {  
            for(int i = 0; i < str.length() ; i = i+chars) 
            {  
                //Dividing string in n equal part using substring()
                String part = str.substring(i, i+chars);  
                newStr[temp] = part;  
                temp++;  
            }  
               System.out.println("On dividing the entered string into "+ n +" equal parts, we have ");  
               for(int i = 0; i < newStr.length; i++) 
               {  
                   System.out.println(newStr[i]);  
               }  
            }  
        }  
}  

Explanation of the Code:
This Java program divides a string into `n` equal parts. 

  • It starts by taking input from the user for the string and the number of parts `n`. 
  • It calculates the length of each part by dividing the string’s length by `n`. 
  • If the string’s length isn’t divisible by `n`, it prints an error message. 
  • If divisible, it initializes an array `newStr` to store the parts. 
  • Using a for-loop, it iterates through the string, extracting substrings of length `chars` and storing them in `newStr`. 
  • Finally, it prints each part of the divided string. The use of `substring()` method facilitates the division of the string into equal segments, ensuring each part is correctly segmented and displayed.

Output:

Enter the string: welcometonew
Enter the value of n: 
2
On dividing the entered string into 2 equal parts, we have 
welcom
etonew

Splitting a string into equal parts in Java is straightforward when the string length is divisible by the desired number of parts. This method ensures each segment is of equal length, aiding in various applications. For more Java programming tutorials and resources, visit Newtum. Happy Coding!



About The Author

Leave a Reply