Javatpoint Logo
Javatpoint Logo

Q. 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 a for loop to traverse the string and divide the string at every chars interval.

The algorithm of the program is given below.

Algorithm

  1. Define a string and define n, i.e., no. of equal parts that string needs to be divided in.
  2. No. of characters (variable chars) in each substring will be found out by dividing the length of the string by n.
  3. If the string cannot be divided into n equal parts, then display an error message.
  4. Else divide the string from i to chars (no. Of character)
  5. Then increment the count by chars and continue dividing the string till you get all the parts of the string.
  6. Print the count.

Complexity:

O(n)

Solution

Python

Output:

Equal parts of given string are 
aaaa
bbbb
cccc

C

Output:

3 equal parts of given string are 
aaaa
bbbb
cccc

JAVA

Output:

3 equal parts of given string are 
aaaa
bbbb
cccc

C#

Output:

3 equal parts of given string are 
aaaa
bbbb
cccc

PHP

Output:

3 equal parts of given string are 
aaaa
bbbb
cccc

Next TopicPrograms List




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials