搜索字符串中单词的频率 (C++)

Searching for the frequency of a word in a string (C++)

我必须编写一个程序,向用户询问一个句子(限制为 1024 个字母),然后向用户询问一个单词,并告诉用户该特定单词在句子中出现了多少次,为一项任务。

我们只允许使用这些库:iostream、string、cstring、cstdlib、cmath 和 fstream。

它应该如何运作的示例:

输入一句话:

输入:你好我叫你好你好

输入一个词来检查频率:

输入:你好

期望输出:单词出现次数:3

实际输出:单词出现次数:25

这是我在朋友的帮助下尝试使用的,但是当我输入一个词进行搜索时,它输出了一个不相关的数字。

int wordFrequency(){
    char sen5[1024];
    int frequency = 0;
    char word[1024];
    cout << "Enter a sentence: " << endl;
    cin.getline(sen5, 1024);
    cout << "Enter a word to check for frequency: " << endl;
    cin.getline(word, 1024);
    for(int i = 0; i < strlen(sen5); i++){
            if(sen5[i] == word[i]){
                    for(int j = 0; j < strlen(word); j++)
                            if(sen5[j] == word[j])
                                    frequency += 1;
            }
    }
    cout << "# of times word occurs: " << frequency << endl;
    return 0;

}

此外,我知道我的编码很糟糕,我的教授是出了名的糟糕,因此我在 class 中苦苦挣扎。感谢任何帮助。

所以朋友,如果你只允许使用isostream,, string, cstring, cstdlib, cmath and fstream.那么你可以用C++语言编程。

所以下面的代码只使用 iostream 进行 input/output 操作。 您也可以使用 string.h 来查找字符串长度,但我已经走了另一条路。

用于查找以下单词出现的函数是:

int countOccurrences(char * str, char * toSearch)
{
    int i, j, found, count;
    int stringLen, searchLen;

    int cou = 0;
    while(str[cou] != '[=10=]'){
        cou++;
    }
    stringLen = cou; 
    cou = 0;  
    while(toSearch[cou] != '[=10=]'){
        cou++;
    }
    searchLen = cou; 

    count = 0;

    for(i=0; i <= stringLen-searchLen; i++)
    {

        found = 1;
        for(j=0; j<searchLen; j++)
        {
            if(str[i + j] != toSearch[j])
            {
                found = 0;
                break;
            }
        }

        if(found == 1)
        {
            count++;
        }
    }

    return count;
}

为了获取输入,你可以在主函数中编写这些东西,然后在主函数中调用上面的函数。下面是代码:

int main()
{
    char str[MAX_SIZE];
    char toSearch[MAX_SIZE];
    int count;

    cout<<"Enter any string: "<<endl;
    cin.getline(str, sizeof(str));
    cout<<"Enter word to search occurrences: "<<endl;
    cin.getline(toSearch, sizeof(toSearch));
    count = countOccurrences(str, toSearch);
    cout<<"Total occurrences of"<< toSearch<<" : "<< count;

    return 0;
}

看来您是编码方面的新手,所以要了解更多信息: 下面是您需要在代码开头添加的代码。 Header 文件并声明 countOccurences 函数。

#include <iostream>
#define MAX_SIZE 100
using namespace std;

int countOccurrences(char * str, char * toSearch);

所以这样你可以只使用 iostream header 来计算字符串中单词的 occurrences/frequency 的数量。