使用标记拆分 C++ std::string,例如“;”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5167625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Splitting a C++ std::string using tokens, e.g. ";"
提问by venkysmarty
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++ 中拆分字符串的最佳方法?可以假设字符串由以 ; 分隔的单词组成。
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.
从我们的指导方针来看,不允许使用 C 字符串函数,也不允许使用 Boost,因为不允许开源。
The best solution I have right now is:
我现在最好的解决方案是:
string str("denmark;sweden;india;us");
string str("丹麦;瑞典;印度;美国");
Above str should be stored in vector as strings. how can we achieve this?
以上 str 应作为字符串存储在 vector 中。我们怎样才能做到这一点?
Thanks for inputs.
感谢您的投入。
回答by Martin Stone
I find std::getline()
is often the simplest. The optional delimiter parameter means it's not just for reading "lines":
我发现std::getline()
往往是最简单的。可选的分隔符参数意味着它不仅用于读取“行”:
#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);
}
}
回答by Fox32
You could use a string stream and read the elements into the vector.
您可以使用字符串流并将元素读入向量。
Hereare many different examples...
这里有许多不同的例子......
A copy of one of the examples:
其中一个示例的副本:
std::vector<std::string> split(const std::string& s, char seperator)
{
std::vector<std::string> output;
std::string::size_type prev_pos = 0, pos = 0;
while((pos = s.find(seperator, pos)) != std::string::npos)
{
std::string substring( s.substr(prev_pos, pos-prev_pos) );
output.push_back(substring);
prev_pos = ++pos;
}
output.push_back(s.substr(prev_pos, pos-prev_pos)); // Last word
return output;
}
回答by hkaiser
There are several libraries available solving this problem, but the simplest is probably to use Boost Tokenizer:
有几个库可以解决这个问题,但最简单的可能是使用 Boost Tokenizer:
#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
std::string str("denmark;sweden;india;us");
boost::char_separator<char> sep(";");
tokenizer tokens(str, sep);
BOOST_FOREACH(std::string const& token, tokens)
{
std::cout << "<" << *tok_iter << "> " << "\n";
}