在本教程中,我们将编写一个程序,将给定的字符串分成N个相等的部分。
如果我们不能将字符串分成N个相等的部分,则打印相同的内容。让我们看看解决问题的步骤。
初始化字符串和N。
使用size方法查找字符串的长度。
检查字符串是否可以分为N个部分。
如果字符串不能分成N个相等的部分,则打印一条消息。
否则,遍历字符串并打印每个部分。
让我们看一下代码。
#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;
}输出结果如果执行上述程序,则将得到以下结果。
ab cd ef gh ij