具有多个分隔符的字符串流

stringstream with multiple delimiters

本文关键字:字符串 分隔符      更新时间:2023-10-16

这是我似乎找不到答案的另一个问题,因为我能找到的每个例子都使用向量,我的老师不会让我们在这个课上使用向量。

我需要使用(任意数量的)空格
一次阅读一本书的纯文本版本一个单词 ' '和(任意数量的)非字母字符作为分隔符;因此,任何数量的空格或标点符号都需要分隔单词。以下是我只需要使用空格作为分隔符时的做法:

while(getline(inFile, line)) {
    istringstream iss(line);
    while (iss >> word) {
        table1.addItem(word);
    }
}

编辑:读入文本的示例,以及我需要如何分离它。

"如果他们知道;你希望它,娱乐会"

以下是需要分隔第一行的方式:

如果

他们

已知

希望

娱乐

愿意

文本将至少包含所有标准标点符号,但也包含省略号...双破折号--等内容。

与往常一样,提前感谢。

编辑:

所以使用第二个字符串流看起来像这样吗?

while(getline(inFile, line)) {
    istringstream iss(line);
    while (iss >> word) {
        istringstream iss2(word);
        while(iss2 >> letter)  {
            if(!isalpha(letter))
                // do something?
        }
        // do something else?
        table1.addItem(word);
    }
}

我还没有测试过这个,因为我现在面前没有 g++ 编译器,但它应该可以工作(除了轻微的C++语法错误)

while (getline(inFile, line))
{
    istringstream iss(line);
    while (iss >> word)
    {
        // check that word has only alpha-numeric characters
        word.erase(std::remove_if(word.begin(), word.end(), 
                                  [](char& c){return !isalnum(c);}),
                   word.end());
        if (word != "")
            table1.addItem(word);
    }
}

如果您可以自由使用 Boost ,您可以执行以下操作:

$ cat kk.txt
If they had known;; you ... wished it, the entertainment.would have

如果需要,您可以自定义tokenizer的行为,但默认值应该足够了。

#include <iostream>
#include <fstream>
#include <string>
#include <boost/tokenizer.hpp>
int main()
{
  std::ifstream is("./kk.txt");
  std::string line;
  while (std::getline(is, line)) {
    boost::tokenizer<> tokens(line);
    for (const auto& word : tokens)
      std::cout << word << 'n';
  }
  return 0;
}

最后

$ ./a.out
If
they
had
known
you
wished
it
the
entertainment
would
have