具有多个分隔符的字符串流
stringstream with multiple delimiters
这是我似乎找不到答案的另一个问题,因为我能找到的每个例子都使用向量,我的老师不会让我们在这个课上使用向量。
我需要使用(任意数量的)空格
一次阅读一本书的纯文本版本一个单词 ' '
和(任意数量的)非字母字符作为分隔符;因此,任何数量的空格或标点符号都需要分隔单词。以下是我只需要使用空格作为分隔符时的做法:
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
相关文章:
- 使用 char 分隔符解析C++中的字符串,但将可重复的字符保留为每个解析的子字符串 (C++ STL) 中的分隔符
- 字符串开头的分隔符
- 尝试将 c 字符串数组与分隔符连接起来
- 根据新的行分隔符从字符串中删除子字符串
- 同一分隔符之间的多个子字符串
- 字符串流分隔符
- 使用正则表达式c++从单词和分隔符之间的字符串中提取所有子字符串
- C++获取两个分隔符之间的字符串并替换它
- 是否存在像C++中那样带有分隔符的C#原始字符串
- 如何从字符串开头到第二个分隔符中提取子字符串?
- 如何使用两个不同的分隔符拆分字符串
- 将子字符串提取到最后 n 个分隔符C++
- 基于 C++ 中的多个字符串分隔符拆分字符串
- 读取 iostream,直到找到字符串分隔符
- 带有字符串分隔符或两个字符的fstream
- 读取直到boost::asio::streambuf中的字符串分隔符
- 使用两个字符串分隔符选择文本文件的一部分
- C++std::ifstream读取字符串分隔符
- 使用多个字符串分隔符拆分字符串
- 使用字符串分隔符(标准C++)解析(拆分)C++中的字符串