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();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章