
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Divide a String in N Equal Parts in C++
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.
#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.
Advertisements