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()

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());
}
}
posted @   Theseus‘Ship  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2021-11-18 十大经典排序算法(转自 www.runoob.com)
Live2D
欢迎阅读『Code-C++-字符串分割』
点击右上角即可分享
微信分享提示