使用了string的find函数和substr函数
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> split(string str, string pattern) {
vector<string> result;
str += pattern;
for (int i = 0; i < str.size(); i++) {
int pos = (int)str.find(pattern, i);
if (pos != string::npos) {
result.push_back(str.substr(i, pos - i));
i = pos + (int)pattern.size() - 1;
}
}
return result;
}
int main() {
string s = "I have a dream!";
vector<string> res = split(s, " ");
return 0;
}
本文介绍了一种使用C++标准库中的string类实现字符串拆分的方法。通过使用find和substr函数,可以将一个字符串按照指定的分隔符进行拆分,并将结果存储在一个vector容器中。这种方法适用于需要对文本数据进行预处理的应用场景。
1万+

被折叠的 条评论
为什么被折叠?



