问题描述:输入一个字符串s,再输入一个分割长度,按照分割长度将字符串分割成n个子串,输出;如果没有,则输出-1。
分析:对字符串按照长度进行分割即可。
解题思路:按照顺序遍历字符串,将n个子串分割后放入容器中输出。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void
split_string(string raw_string,
int dimension,
int offset,
int split_scale,
vector<string>& vs_capacity) {
if (offset + split_scale > dimension || offset > dimension || split_scale < 0)
return;
string sub_temp = raw_string.substr(offset, split_scale);
vs_capacity.push_back(sub_temp);
split_string(raw_string, dimension, offset + 1, split_scale, vs_capacity);
}
int main(int argc, char** argv) {
string input_string;
int split_scale;
cin >> input_string >> split_scale;
vector<string> vs_capacity;
split_string(input_string, input_string.length(), 0, split_scale, vs_capacity);
if (vs_capacity.size() < 1)
cout << -1;
else {
for (int i = 0; i < vs_capacity.size(); i++)
cout << vs_capacity[i] << " ";
}
cout << endl;
system("pause");
return 0;
}