Divide a string in N equal parts

StringViews 2659

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


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

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


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;
   //size of parts
   int part_size = length/N;
   for (int i = 0; i< length; i++)
       if (i%part_size == 0)
          //Next line(seperator)
int main()
    //Input string
    char string[] = "stringlength";
    cout<<"Input string: ";
    for (int i = 0; i < strlen(string); ++i)
    int k;
    cout<<"\nEnter the value of N: ";
    divideString(string, k);
    return 0;

Try It


Translate »