分割字符串

问题描述:输入一个字符串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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值