[C/C++] 简单实现split函数:按字符分割字符串

记录一下

1. 分割函数

// 字符串 str 通过字符 target 进行分割 vector<string> split(const string& str, char target) { vector<string> res; int pos = 0; while (pos < str.size()) { // 移动到片段开头 while (pos < str.size() && str[pos] == target) { pos++; // // 如果空串也需要被分割出来,则需要加上注释这部分 // if (pos > 0 && str[pos] == str[pos - 1]) { // res.push_back(""); // } } // 记录片段开头 int start = pos; // 移动到片段末尾的下一个下标 while (pos < str.size() && str[pos] != target) { pos++; } if (pos < str.size()) { // 切割字符串,并切割的片段添加到数组中 res.push_back(str.substr(start, pos - start)); } } return res; }

2. 完整代码

#include <bits/stdc++.h> using namespace std; // 字符串 str 通过字符 target 进行分割 vector<string> split(const string& str, char target) { vector<string> res; int pos = 0; while (pos < str.size()) { // 移动到片段开头 while (pos < str.size() && str[pos] == target) { pos++; // // 如果空串也需要被分割出来,则需要加上注释这部分 // if (pos > 0 && str[pos] == str[pos - 1]) { // res.push_back(""); // } } // 记录片段开头 int start = pos; // 移动到片段末尾的下一个下标 while (pos < str.size() && str[pos] != target) { pos++; } if (pos < str.size()) { // 切割字符串,并切割的片段添加到数组中 res.push_back(str.substr(start, pos - start)); } } return res; } int main() { string str; getline(cin, str); char target; cin >> target; vector<string> res = split(str, target); for (int i = 0; i < res.size(); ++i) { cout << "\"" << res[i] << "\""; cout << (i + 1 != res.size() ? ", " : "\n"); } return 0; }

测试

# 输入: # @@hello@@world@@ # @ # 输出: # 1)不包含空串 "hello", "world" # 2)包含空串 "", "hello", "", "world", ""
posted @   小贼的自由  阅读(264)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示