使用标记拆分C++ std :: string,例如";"

ven*_*rty 75 c++

可能重复:
如何在C++中拆分字符串?

在C++中拆分字符串的最佳方法?可以假设该字符串由分隔的字组成;

从我们的指南角度来看,不允许使用C字符串函数,也不允许使用Boost,因为不允许使用安全锥形开源.

我现在最好的解决方案是:

string str("denmark; sweden; india; us");

str上面应该作为字符串存储在vector中.我们怎样才能做到这一点?

感谢您的投入.

Mar*_*one 177

我发现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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • +1:哇,从未考虑过使用带有`istringstream`的`getline`. (5认同)
  • 好方法!尽管写得很仔细.起初我无法编译这个...因为我一直在分隔符上使用双引号(getline(f,s,";")).#FeelingStupid. (5认同)
  • 那是我一生中见过的使用stringstream的最漂亮的代码!谢谢 (2认同)

Fox*_*x32 13

您可以使用字符串流并将元素读入向量.

这里有很多不同的例子......

其中一个例子的副本:

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;
}
Run Code Online (Sandbox Code Playgroud)


hka*_*ser 11

有几个库可以解决这个问题,但最简单的可能是使用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";
}
Run Code Online (Sandbox Code Playgroud)