可能的复制品: 如何在 C + + 中拆分字符串
在 C + + 中分割字符串的最好方法是什么?可以假定该字符串由以下单词组成:
从我们的指南线的角度来看,C 字符串函数是不允许的,而且 Boost 也不允许使用,因为安全问题开源是不允许的。
我现在最好的解决办法是:
String str (“ denmark; sweden; india; us”) ;
上面的 str 应该以字符串的形式存储在矢量中。我们怎样才能做到这一点呢?
谢谢你的建议。
You could use a string stream and read the elements into the vector.
Here are 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; }
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); } }
There are several libraries available solving this problem, but the simplest is probably to use 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"; }