字符串分割split

借助strtok分割string类型的字符串,将结果保存在vector<string>中

思路:先将整个string字符串转换为char*类型,分割后得到char*类型的子字符串,将子字符串转换为string类型,并存入结果数组中。

编译软件:vs2013

代码:

#include <iostream>
#include <vector>
#include <stdlib.h>
#include <string>
#include <string.h>
using namespace std;

vector<string> split(const string& str, const string& delim) {
	vector<string> res;
	if ("" == str) return res;
	//先将要切割的字符串从string类型转换为char*类型
	char * strs = new char[str.length() + 1]; 
	strcpy(strs, str.c_str());

	char * d = new char[delim.length() + 1];
	strcpy(d, delim.c_str());

	char *p = strtok(strs, d);
	while (p) {
		string s = p; //分割得到的字符串转换为string类型
		res.push_back(s); //存入结果数组
		p = strtok(NULL, d);
	}

	return res;
}

void test1() { //空字符串
	cout << "******test1****** " << endl;
	string s = "";

	std::vector<string> res = split(s, " ");
	for (int i = 0; i < res.size(); ++i)
	{
		cout << res[i] << endl;
	}
}

void test2() { //只有一个字符串
	cout << "******test2****** " << endl;
	string s = "my";

	std::vector<string> res = split(s, " ");
	for (int i = 0; i < res.size(); ++i)
	{
		cout << res[i] << endl;
	}
}

void test3() { //正常字符串
	cout << "******test3****** " << endl;
	string s = "my name is lmm   ";//连续多个空格,空格会被过滤掉

	std::vector<string> res = split(s, " ");
	for (int i = 0; i < res.size(); ++i)
	{
		cout << res[i] << endl;
	}
}


int main() {

	test1();
	test2();
	test3();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/cai_niaocainiao/article/details/81775476