在句子中查找单词

Finding words in sentences

本文关键字:单词 查找 句子      更新时间:2023-10-16

我有一个编程作业无法完成。这一部分正在杀死我。

接受来自用户的一些文本。接受需要搜索的字符串。您的程序应该打印在文本中找到的字符串的出现次数,以及找到模式的位置。查看以下示例输出:

示例输出: 输入文本:"叫我以实玛利。几年前——不管确切地花了多久——我的钱包里很少或根本没有钱,在岸上也没有什么特别让我感兴趣的,我想我会航行一会儿,看看世界的水域。这是我驱除脾脏和调节血液循环的一种方式"

要搜索的字符串 - "几年前"

出现次数 – 1

找到的位置 – 18

这是我的函数:

void getText()
{
    string itext, word;
    int position;
    bool done =  false;
    cout << "Enter some text" << endl;
    cin >> itext;
    cout << "Enter the word or phrase to wish to find" << endl;
    cin >> word;
    char text[itext.length()];
    char search[word.length()];
    for(int i = 0; i < itext.length(); i++)
    {
        for(int j = 0; j < word.length(); j++)
        {
            if(text[i] == search[j])
            {
                position = i;
                cout << position;
            }
        } 
     }
}

这可能会让你开始:(来自Knuth-Morris-Pratt算法的伪代码)

algorithm kmp_search:
    input:
        an array of characters, S (the text to be searched)
        an array of characters, W (the word sought)
    output:
        an integer (the zero-based position in S at which W is found)
    define variables:
        an integer, m ← 0 (the beginning of the current match in S)
        an integer, i ← 0 (the position of the current character in W)
        an array of integers, T (the table, computed elsewhere)
    while m + i < length(S) do
        if W[i] = S[m + i] then
            if i = length(W) - 1 then
                return m
            let i ← i + 1
        else
            if T[i] > -1 then
                let m ← m + i - T[i], i ← T[i]
            else
                let i ← 0, m ← m + 1
    (if we reach here, we have searched all of S unsuccessfully)
    return the length of S

http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm

编辑:更简单并使用c ++ std库:

#include <string>
#include <vector>
int main ()
{
  std::string str ("There are two needles in this haystack with needles.");
  std::string str2 ("needle");
  // different member versions of find in the same order as above:
  std::size_t found = 0;
  int matches = 0;
  std::vector<size_t> positions;
  while( found = str.find(str2) != std::string::npos) {
      matches++;
      positions.push_back(found);
    }
}

如果你在这个任务中使用std::string而不是char[],你可以让你的生活更轻松。您所要做的就是将文本加载到 std::string 中,然后使用其 find 方法,如下所述:http://www.cplusplus.com/reference/string/string/find/

顺便说一句,我不确定这些行是否可以工作,因为您可以仅使用常量表达式长度创建非动态数组

char text[itext.length()];
char search[word.length()];