c++实现split()字符串切片

IDE是VS2013.

#include
#include 
#include
using namespace std;
vector split(const string& src, string separate_character)
{
	vector strs;
	int separate_characterLen = separate_character.size();//分割字符串的长度,这样就可以支持如“,,”多字符串的分隔符
	int lastPosition = 0, index = -1;
	while (-1 != (index = src.find(separate_character, lastPosition)))
	{
		strs.push_back(src.substr(lastPosition, index - lastPosition));
		lastPosition = index + separate_characterLen;
	}
	string lastString = src.substr(lastPosition);//截取最后一个分隔符后的内容
	if (!lastString.empty())
		strs.push_back(lastString);//如果最后一个分隔符后还有内容就入队
	return strs;
}
int _tmain(int argc, _TCHAR* argv[])
{
	string s = "12.45.78";
	string del =".";
	vector strs = split(s,del);
	for (int i = 0; i < strs.size(); i++)
	{
		cout << strs[i]<<' ';
	}
	cout << endl;
	system("pause");
	return 0;
}
运行结果:

c++实现split()字符串切片_第1张图片

你可能感兴趣的:(c++笔记)