[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", ""
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具