【问题标题】:using iterator to get phrases in a string.使用迭代器获取字符串中的短语。
【发布时间】:2014-04-03 04:22:40
【问题描述】:

我有包含许多句子的向量,例如“你好,你好吗”。我希望能够从句子中提取大小为 2 和 5 的短语,然后将其存储在另一个向量中。例如,从上面的字符串中,我希望得到 "hello there" "hello there how" “你好,你好吗”和“你好,你好吗”。

我尝试将句子拆分为单独的单词并将它们存储在一个向量中:

while( getline(stream, word, ' ') )
{

    vecWord.push_back(word);
}

这删除了所有空格并存储了每个单词。我知道迭代器指向向量中的每个元素。如何使用迭代器指向每个元素(也就是每个单词)并将它们组合成 2 - 5 的大小

任何帮助将不胜感激

【问题讨论】:

  • 那么,对于“a b c d e f g”,给定子字符串“c d e”,您将打印“c d e”、“c d e f”和“c d e f g”?
  • 是的。我希望能够获得字符串的“短语”。这就是为什么我考虑使用迭代器。有可能吗?
  • 如果我理解正确,是的。歧义来自“短语”的使用。
  • 我将不得不编辑这篇文章。有点模糊

标签: c++ vector iterator


【解决方案1】:

试试这个。给定all,它是所有单词的列表,target,它是所需子字符串中的单词列表。这可以分解为过于独立的问题。首先,找到子串,然后找到包含它的所有以下子串。第一部分与如何在字符串中查找子字符串的一般问题非常相似。即如何在“abc7845xyz”中找到“45x”。如果掌握如何使用迭代器是你在做什么的想法,我建议查找使用普通 C 数组索引样式迭代编写的字符串搜索算法,并尝试将它们转换为迭代器。

for(auto i = all.begin();i < all.end() - target.size();i++){
    auto temp_i = i;
    bool found = found = true;
    for(auto j = target.begin();found && j < target.end();j++, temp_i++)
        found = *temp_i == *j;

    // Substring found, so print all subsequent substrings containing it.
    if(found){
        auto start = i;
        for(auto end = i + target.size();end < all.end();end++){
           for(auto j = start;j <= end;j++)
               cout << j << " ";
           cout << endl;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多