How to Divide a string into N equal parts in C++
In this tutorial, we will learn how to divide a string into N equal parts in C++. Also, we have given a string and value of N and our task is to divide this string.
For example:
- Given string: “Better to reduce time complexity”
- Given the value of N= 4
- So, we have to divide this string into 4 equal parts.
- Output:
Better t o reduce time co mplexity
Approach:
To illustrate:
- Firstly, we will get the size of the string over here.
- Now, to get the size, we will include string.h header file.
- Further, we will get the size of the part.
- The size of the part is:
size_of_part=total_string_length/N - Finally, iterate through input string.
- If the Index number becomes multiple of size_of_part, then put a separator over there that is (\n).
Also, you may like:
How to remove or eliminate the extra spaces from a given string in C++
Divide a string into N equal parts
Implementation:
#include<iostream>
#include<string.h>
using namespace std;
class separator
{
// Function for N equal parts
public:
void separatestring(char str[], int n)
{
int size_of_str = strlen(str);
int i;
int size_of_part;
// Check for the string if it can be divided or not
if (size_of_str % n != 0)
{
cout<<"Invalid";
return;
}
// Get the size of parts to get the division
size_of_part = size_of_str / n;
for (i = 0; i< size_of_str; i++)
{
if (i % size_of_part == 0)
cout<<endl;
cout<< str[i];
}
}
};
int main()
{
separator s;
char str[] = "Better to reduce time complexity";
// Print 4 equal equal parts
s.separatestring(str, 4);
return 0;
}
Output Explanation:
INPUT: "Better to reduce time complexity"
OUTPUT:
Better t
o reduce
time co
mplexityThis is how we can divide a string into n equal parts in C++.
Also learn:
Leave a Reply