【问题标题】:Separate a sentense into a vector of its words将一个句子分成其单词的向量
【发布时间】:2020-08-22 20:08:34
【问题描述】:
    std::string rule = "aa|b";
    std::string curr;
    std::vector<std::string> str;
    int k = 0;
    while (k < rule.size())
    {
        while (rule[k] != '|' )
        {
            curr.push_back(rule[k]);
            k++;
        }
        str.push_back(curr);
        curr.clear();
        k++;
    }
    for (size_t i = 0; i < str.size(); i++)
    {
        std::cout << str[i] << "\n";
    }

我只想将“aa”和“b”分开并将其作为字符串放在向量中。它向我抛出了这个异常:

Unhandled exception at 0x7A14E906... An invalid parameter was passed to a function that considers invalid parameters fatal;

【问题讨论】:

  • 如果字符串的最后一个字符不是|,你的内循环不会跑到字符串的末尾吗?
  • 是的,当我尝试使用“aa|b|”时它工作得很好,但如何解决呢?
  • 有一种更简单的方法来创建子字符串:stackoverflow.com/questions/14265581/…
  • 到达终点就停下来:while (k &lt; str.size() &amp;&amp; rule[k] != '|')

标签: c++ string function vector


【解决方案1】:

这个循环

while (rule[k] != '|' )
{
    curr.push_back(rule[k]);
    k++;
}

在您找到最后一个 '|' 后,将继续无止境地进行下去,结果是未定义的行为。

使用stringstream'|' 作为“行”分隔符更容易解决。

std::istringstream is(rule);
std::string word;
while (std::getline(is, word, '|'))
{
    str.push_back(word);
}

【讨论】:

    【解决方案2】:

    您也可以简单地使用boost::split

       #include <boost/algorithm/string.hpp>
    
       std::vector<std::string> strs;
       boost::split(strs, "this|is|a|simple|example", boost::is_any_of("|"));
    

    【讨论】:

      猜你喜欢
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      • 1970-01-01
      相关资源
      最近更新 更多