C++分割字符串方法

C++标准目前没有提供分割字符串的方法,但可以自己实现之。

测试代码如下:

#include <vector>
#include <string>
#include <iostream>

std::vector<std::string> Split(const std::string& str, const char* delim)
{
	std::vector<std::string> result;
	size_t delim_len = strlen(delim);
	std::string::size_type pos1 = 0;
	std::string::size_type pos2 = str.find(delim);

	while (pos2 != std::string::npos)
	{
		result.emplace_back(str, pos1, pos2 - pos1);

		pos1 = pos2 + delim_len;
		pos2 = str.find(delim, pos1);
	}

	if (pos1 != str.length())
	{
		result.emplace_back(str, pos1);
	}

	return result;
}

int main()
{
	std::string str = "hello|world|hi|cpp";

	auto res = Split(str, "|");

	for (const auto& item : res)
	{
		std::cout << item << std::endl;
	}

	std::cin.get();
}
原文地址:https://www.cnblogs.com/demon90s/p/15612975.html