AIGC标识 Code-C++-字符串分割

Code-C++-字符串分割

转自【C++中string如何实现字符串分割函数split()——4种方法 - CSDN App】http://t.csdnimg.cn/8iWb7

  • stringstream getline()
  • string find() substr()
  • c char strtok() strtok_r()
  • regex_token_iterator<>

getline()

void Stringsplit(string str,const const char split)
{
	istringstream iss(str);	// 输入流
	string token;			// 接收缓冲区
	while (getline(iss, token, split))	// 以split为分隔符
	{
		cout << token << endl; // 输出
	}
}

find() substr()

// 使用字符分割
void Stringsplit(const string& str, const char split, vector<string>& res)
{
	if (str == "")		return;
	//在字符串末尾也加入分隔符,方便截取最后一段
	string strs = str + split;
	size_t pos = strs.find(split);
 
	// 若找不到内容则字符串搜索函数返回 npos
	while (pos != strs.npos)
	{
		string temp = strs.substr(0, pos);
		res.push_back(temp);
		//去掉已分割的字符串,在剩下的字符串中进行分割
		strs = strs.substr(pos + 1, strs.size());
		pos = strs.find(split);
	}
}
// 使用字符串分割
void Stringsplit(const string& str, const string& splits, vector<string>& res)
{
	if (str == "")		return;
	//在字符串末尾也加入分隔符,方便截取最后一段
	string strs = str + splits;
	size_t pos = strs.find(splits);
	int step = splits.size();
 
	// 若找不到内容则字符串搜索函数返回 npos
	while (pos != strs.npos)
	{
		string temp = strs.substr(0, pos);
		res.push_back(temp);
		//去掉已分割的字符串,在剩下的字符串中进行分割
		strs = strs.substr(pos + step, strs.size());
		pos = strs.find(splits);
	}
}

strtok()

split 表示分隔字符集合:strtok() 会把其中每个字符都作为分隔符,而不是把整个 split 字符串视为一个分隔符。

void Stringsplit(const string& str, const string& split, vector<string>& res)
{
	char* strc = new char[str.size() + 1];
	strcpy(strc, str.c_str());   // 将str拷贝到 char类型的strc中
	char* temp = strtok(strc, split.c_str());
	while (temp != NULL)
	{
		res.push_back(string(temp));		
		temp = strtok(NULL, split.c_str());	// 下一个被分割的串
	}
	delete[] strc;
}

void Stringsplit(const string& str, const char split, vector<string>& res)
{
	Stringsplit(str, string(1,split), res);	// 调用上一个版本的Stringsplit()
}

regex_token_iterator<>

void Stringsplit(const string& str, const string& split, vector<string>& res)
{
	//std::regex ws_re("\\s+"); // 正则表达式,匹配空格 
	std::regex reg(split);		// 匹配split
	std::sregex_token_iterator pos(str.begin(), str.end(), reg, -1);
	decltype(pos) end;              // 自动推导类型 
	for (; pos != end; ++pos)
	{
		res.push_back(pos->str());
	}
}

本文修订依据:The Open Group Base Specifications Issue 7(IEEE Std 1003.1-2017)的 strtok() 规范页面。该函数将第二个参数中的每个字节视为分隔符;本文仅补充这一语义说明,未改写示例代码。

AI 修改声明: 本文由 LLM 协助修订,最近修改时间:2026-09-25 11:15(UTC+08:00)。修订仅说明 strtok() 的分隔字符集合语义。

posted @ 2023-11-18 17:44  Theseus‘Ship  阅读(60)  评论(0)    收藏  举报
Live2D