Divide a string in N equal parts in C++ Program

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that divides the given string into N equal parts.

If we can't divide the string into N equal parts, then print the same thing. Let's see the steps to solve the problem.

  • Initialize the string and N.

  • Find the length of the string using the size method.

  • Check whether the string can be divided into N parts or not.

  • If string can't divide into N equal parts, then print a message.

  • Else iterate through the string and print each part.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void divideTheString(string str, int n) {
   int str_length = str.size();
   if (str_length % n != 0) {
      cout << "Can't divide string into equal parts" << endl;
      return;
   }
   int part_size = str_length / n;
   for (int i = 0; i < str_length; i++) {
      if (i != 0 && i % part_size == 0) {
         cout << endl;
      }
      cout << str[i];
   }
   cout << endl;
}
int main() {
   string str = "abcdefghij";
   divideTheString(str, 5);
   return 0;
}

Output

If you execute the above program, then you will get the following result.

ab
cd
ef
gh
ij

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 27-Jan-2021 12:47:57
Advertisements