【问题标题】:Splitting a line in C/C++ using whitespace as delimiter [duplicate]使用空格作为分隔符在 C/C++ 中拆分一行 [重复]
【发布时间】:2011-05-09 08:56:58
【问题描述】:

可能重复:
How do I tokenize a string in C++?

伪代码:

    Attributes[] = Split line(' ')

怎么做?

我一直在这样做:

  char *pch;
  pch = strtok(line," ");
  while(pch!=NULL)
  {
      fputs ( pch, stdout ); 


  }

并获得一个未写入的、卡住的退出文件。这有什么问题吗? 好吧,这件事甚至不符合我的伪代码要求,但我对如何将标记(作为 char 数组)索引到我的数组感到困惑,我想我应该写一个 2-dim 数组?

【问题讨论】:

  • 解决方案因您使用的是 C 还是 C++ 而不同。
  • 下面的一些示例怎么样:codeproject.com/KB/recipes/Tokenizer.aspx 它们非常高效且有些优雅。字符串工具包库使 C++ 中的复杂字符串处理变得简单易行。

标签: c++ c


【解决方案1】:

使用strtok" " 作为分隔符。

【讨论】:

  • 这对 C 来说很棒,对于 C++,请参阅我的回答中的相关问题。
【解决方案2】:

这不是一个重复 - 对于 C++,请参阅 @Zunino 接受的答案 here 并投票赞成。

下面的基本代码,但要看到答案的全部辉煌优雅,您将不得不单击它。

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>

int main() {
    using namespace std;
    string sentence = "Something in the way she moves...";
    istringstream iss(sentence);
    copy(istream_iterator<string>(iss),
             istream_iterator<string>(),
             ostream_iterator<string>(cout, "\n"));
}

这取决于默认情况下istream_iterator 将空格作为其分隔符。生成的标记在单独的行上写入cout(每个分隔符在ostream_iterator 的构造函数重载中指定)。

【讨论】:

    【解决方案3】:

    最简单的方法是boost::split:

    std::vector<std::string> words;
    boost::split(words, your_string, boost::is_space());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-07
      • 2018-08-18
      • 2022-01-13
      • 2011-01-17
      • 2011-03-10
      • 1970-01-01
      • 2018-06-09
      • 2012-03-01
      相关资源
      最近更新 更多