c++ string split function

#include <string>
#include <vector>
#include <regex>

struct SplitListItem
{
	std::string key;
	std::string value;
};

std::vector<SplitListItem> splitString(std::string origenString, std::regex pattern)
{
	std::smatch result;
	std::string::const_iterator iterStart = origenString.begin();
	std::string::const_iterator iterEnd = origenString.end();


	std::vector<std::string> splitList = {};
	std::vector<std::string> splitKeys = {};
	std::vector<SplitListItem> resultSplitList = {};

	while (regex_search(iterStart, iterEnd, result, pattern))
	{
		splitList.emplace_back(iterStart, result[0].first);
		splitKeys.push_back(result[0].str());
		iterStart = result[0].second;
	}
	splitList.emplace_back(iterStart, iterEnd);


	for (size_t i = 0; i < splitList.size(); i++)
	{
		resultSplitList.push_back(SplitListItem{ i > 0 ? splitKeys[i - 1] : "",  splitList[i] });
	}
	return resultSplitList;
}


std::vector<SplitListItem>  r = splitString("game.exe+009E820C+4+8-4", (std::regex)"[+-]");
for (size_t i = 0; i < r.size(); i++)
{
    std::cout << r[i].key << std::endl;
    std::cout << r[i].value << std::endl;
}
vector<string> string_split(string str, regex reg)
{
	smatch m;
	string::const_iterator iterStart = str.begin();
	string::const_iterator iterEnd = str.end();

	vector<string> resultSplitList = {};

	while (regex_search(iterStart, iterEnd, m, reg))
	{
		resultSplitList.emplace_back(iterStart, m[0].first);
		iterStart = m[0].second;
	}
	resultSplitList.emplace_back(iterStart, iterEnd);
	return resultSplitList;
}

string_split(str, regex("\\s+"));
posted @ 2020-07-22 13:54  Ajanuw  阅读(205)  评论(0编辑  收藏  举报