C++帮助:使用数组和循环在文本中查找单词

C++ Help: Finding words in text with arrays and loops

本文关键字:文本 查找 单词 循环 帮助 数组 C++      更新时间:2023-10-16

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

对于我的函数

我不知道我做错了什么,我需要帮助!

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;
            }
        } 
    }

}

第一个文本和搜索不会初始化为 itext 和 word。其次,您的 if 应该是 == 而不是 = 。第三,你的检查方法是错误的,这是你需要弄清楚的(你需要做功课)。

我不会为你做硬件,但我会给出一些应该可以帮助你到达那里的指示。

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

这是没有道理的。我什至不确定它是否合法,但如果是,这仍然是一个坏主意,因为您将没有空间容纳您的空终止符。此外,您已经将值存储在 itextword 中,那么为什么要将它们放在其他地方呢?

string有一个查找方法(字符串::find)尝试使用它查找从零开始的实例,然后在找到的位置 + 1 处再次搜索。重复此操作,直到搜索失败。

首先,你不能创建具有动态长度的数组。

其次,我们在比较两个值时if语句中使用==

最后,在这里我使用string.find("searchPhrase", startIndex)重新编码您的解决方案。 希望对您有所帮助。

#include <iostream>
#include <string>
using namespace std;
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;
    int startIndex = 0 ;
    while( itext.find(word,startIndex) != -1)
    {
        cout<<"Found at "<<itext.find(word,startIndex)<<endl;
        startIndex = itext.find(word,startIndex) + 1; // we update start point of next seatch
    }
}

这应该为您提供一些基于代码解决它的选项的方向。

字符数组已删除。 因为未初始化,也不需要。

内部循环应该结束,然后你才能判断是否找到了单词。

要阅读整个句子,您需要使用getline。

比较是通过使用==而不仅仅是=。我更喜欢!=这意味着不平等。

#include <iostream>
#include <string>
using namespace std;
int main()
{
     string text, word;
    int position;
    bool done =  false;
    cout << "Enter some text" << endl;
    getline(cin, text); //if you want line with white spaces...
    cout << "Enter the word or phrase to wish to find" << endl;
    cin >> word;
    size_t i,j;
    for(i = 0; i < text.length(); i++)
    {
        for(j = 0; j < word.length(); j++)
        {
            if(text[i+j] != word[j])
            {
                break;//inner for
            }
        } 
        if(j == word.length()){ //means inner loop run till the end.
            position = i;
            cout << position<<endl;
        }
    }
    return 0;
}

输出:

Enter some text
abcd abc abcd
Enter the word or phrase to wish to find
abc
0
5
9