使用令牌拆分C ++ std :: string,例如“; [英] Splitting a C++ std::string using tokens, e.g. ";"
问题描述
可能重复:
如何在C ++中拆分字符串?
Possible Duplicate:
How to split a string in C++?
在C ++中分割字符串的最好方法是什么?字符串可以假定由以下分隔的单词组成:
Best way to split a string in C++? The string can be assumed to be composed of words separated by ;
从我们的指南看来,不允许使用C字符串函数,并且Boost也不允许使用因为安全策略不允许开源。
From our guide lines point of view C string functions are not allowed and also Boost is also not allowed to use because of security conecerns open source is not allowed.
我现在最好的解决方案是:
The best solution I have right now is:
string str(denmark; sweden; india; us);
string str("denmark;sweden;india;us");
上面的str应该作为字符串存储在向量中。我们如何实现这个?
Above str should be stored in vector as strings. how can we achieve this?
感谢您的输入。
推荐答案
我发现std :: getline()通常是最简单的。可选的delimiter参数意味着它不只是用于读取lines:
I find std::getline() is often the simplest. The optional delimiter parameter means it's not just for reading "lines":
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> strings;
istringstream f("denmark;sweden;india;us");
string s;
while (getline(f, s, ';')) {
cout << s << endl;
strings.push_back(s);
}
}
这篇关于使用令牌拆分C ++ std :: string,例如“;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!