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)) |
| { |
| 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); |
| |
| |
| 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(); |
| |
| |
| 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()); |
| 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); |
| } |
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()); |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
2021-11-18 十大经典排序算法(转自 www.runoob.com)