[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", ""