【问题标题】:Splitting a C++ std::string using tokens, e.g. ";" [duplicate]使用标记拆分 C++ std::string,例如“;” [复制]
【发布时间】:2011-07-07 06:14:55
【问题描述】:

可能重复:
How to split a string in C++?

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

从我们的指导方针来看,不允许使用 C 字符串函数,也不允许使用 Boost,因为不允许开源。

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

string str("丹麦;瑞典;印度;美国");

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

感谢您的意见。

【问题讨论】:

  • 我不认为这应该被标记为重复,另一个问题提倡优雅而不是效率,我不同意并因此避免。
  • "HOW TO SPLIT A STRING IN C++" 列出了一些不错的选择。

标签: c++


【解决方案1】:

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

Here 有很多不同的例子...

其中一个示例的副本:

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;
}

【讨论】:

  • 在链接中提供的空间用作分隔符我如何指定“;”作为分隔符
  • 有很多例子,有的带有空格分隔符,有的带有变量分隔符
  • 更多示例可以在这个问题中找到。 stackoverflow.com/q/53849/2298
  • 请通过 ref-to-const 将字符串接受到函数中!
  • 哦,拼写为“examples”;)
【解决方案2】:

我发现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);
    }
}

【讨论】:

  • 好方法!不过要认真写。起初我无法编译这个......因为我一直在分隔符上使用双引号(getline(f,s,“;”))。 #FeelingStupid。
  • 知道如何根据另一个字符串拆分字符串吗?例如,将"abdecfdcfe" 拆分为字符串"de",这将返回{"ab", "cfdcfe"}。还有什么方法可以将字符串拆分为多个字符?和上面的例子一样,答案是{"ab", "cf", "cf"}
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 2016-02-26
    • 2012-07-01
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    相关资源
    最近更新 更多