Home » Interview Questions » String Interview Questions » Divide a string in N equal parts

Divide a string in N equal parts


()

Write a program to divide the given string into N equal parts. (N is input)

Examples

a) Input string : “stringlength”, N = 2
Output :
string
length

b) Input string : “tutorialcup”, N = 3
Output : Invalid input!
Because, string cannot be divided into N equal parts.

Algorithm

a. Get the size of the given string using strlen() and store in length.

b. If length % N is not equal to zero, print invalid input. Because, string cannot be divided into N equal parts for given N.

c. Get size of each part, part_size = length/N

d. Run loop through the given input string. In this loop, after printing every part_size characters use separator \n or endl.

C++ Program

#include <bits/stdc++.h>

using namespace std;
 
//Function to divide into N equal parts
void divideString(char *string, int N)
{
   int length = strlen(string);
   //checking if string can be divided in N equal parts
   //If not print invalid input
   if (length%N != 0)
   {
       cout<<"Invalid Input!"<<endl;
       return;
   }
   //size of parts
   int part_size = length/N;
   for (int i = 0; i< length; i++)
   {
       if (i%part_size == 0)
       {
          //Next line(seperator)
          cout<<endl; 
       }
       cout<<string[i];
   }
}
 
int main()
{
    //Input string
    char string[] = "stringlength";
    cout<<"Input string: ";
    for (int i = 0; i < strlen(string); ++i)
    {
       cout<<string[i];
    }
    int k;
    cout<<"\nEnter the value of N: ";
    cin>>k;
    divideString(string, k);
    return 0;
}

Try It

 

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote Count

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions