How to Split a String in C++?
- 时间:2020-09-09 13:16:32
- 分类:网络文摘
- 阅读:124 次
In C++, there is no inbuilt split method for string. It is very useful to split a string into a vector of string. We can use the following string split method to split a string into a vector or string using the stringstream class.
1 2 3 4 5 6 7 8 9 | vector<string> split(const string& text) { string tmp; vector<string> stk; stringstream ss(text); while(getline(ss,tmp,' ')) { stk.push_back(tmp); } return stk; } |
vector<string> split(const string& text) {
string tmp;
vector<string> stk;
stringstream ss(text);
while(getline(ss,tmp,' ')) {
stk.push_back(tmp);
}
return stk;
}Example usage:
1 2 3 4 5 6 7 8 | int main() { string str = "This is me"; vector<string> words = split(str); // words = ["This", "is", "me"]; for (const auto &n: words) { cout << n << endl; } } |
int main() {
string str = "This is me";
vector<string> words = split(str);
// words = ["This", "is", "me"];
for (const auto &n: words) {
cout << n << endl;
}
}And of course, you can easily add the support for custom delimiter such as split a string by comma or colon (IP addresses):
1 2 3 4 5 6 7 8 9 | vector<string> split(const string& text, char delimiter) { string tmp; vector<string> stk; stringstream ss(text); while(getline(ss,tmp, delimiter)) { stk.push_back(tmp); } return stk; } |
vector<string> split(const string& text, char delimiter) {
string tmp;
vector<string> stk;
stringstream ss(text);
while(getline(ss,tmp, delimiter)) {
stk.push_back(tmp);
}
return stk;
}Let’s hope that a string split function will be added to the string class in future C++ releases!
–EOF (The Ultimate Computing & Technology Blog) —
推荐阅读:如何获取wordpress外循环的自定义栏目 为wordpress媒体文件添加分类目录和标签的方法 小技巧:在wordpress仪表盘中双击评论内容可编辑评论 解决wordpress自动更新失败无法进入后台的方法及升级失败原因 通过.htaccess限制访问IP 保护wordpress后台安全 第一次坐公交车作文100字 人生思考作文800字 上海东方明珠塔作文400字 冬日趣事作文100字 妈妈母亲节快乐作文300字
- 评论列表
-
- 添加评论