Divide a string in N equal parts


StringViews 3012

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

 

Translate »