How to Split a String in C++?
- 时间:2020-09-09 13:16:32
- 分类:网络文摘
- 阅读:122 次
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) —
推荐阅读:红枣维生素含量高 喝大枣水养肝排毒 黑木耳营养丰富对健康有五大好处 香蕉和橘子能起到解毒护肝的作用 吃葡萄、喝葡萄酒能帮助调节性功能 绿茶、红茶、青茶、黑茶、白茶和黄茶 奶茶多添加奶精 长期食用会引发心脏病 奶茶调查:街头奶茶店调香味多用奶精 适合秋天食用的养肺食谱可滋阴润肺 哪些食物可以起到止咳润肺的作用 食物的禁忌:中医如何区分食物的寒热性
- 评论列表
-
- 添加评论