gpt4 book ai didi

c - 如何计算文本文件中相互重叠的单词

转载 作者:太空宇宙 更新时间:2023-11-04 04:13:58 24 4
gpt4 key购买 nike

我正在用户选择查找的 txt 文件中搜索 特定的单词和符号 (&) ,已经由 图书馆。我为每个单词做了一个单独的函数(因为我 真的不知道如何组合它们)但我无法弄清楚 执行/同时搜索功能。

我已经为每个单词做了一个单独的功能,但我无法弄清楚 do/while 搜索功能本质上是我的问题 具有组合功能和搜索 2 部分的功能 只字不提。我想数 while 和 do/while 分开。

 #include < stdio.h >
#include < stdlib.h >
#include < string.h >
#define BUFFER_SIZE 1000

/* Function declarations. How do I combine them all? */
int CountOccurrences ( FILE *fptr, char *word );

int main()
{
FILE *fptr; // name

SetConsoleCP (1251); // so that it runs with my language
SetConsoleOutputCP (1251);

char path[100];

// The 4 words and the symbol I am searching for.

char word[]= "while";
char word1[]= "for";
char word2[]= "&";
char word3[]= "do{ }while";

int wCount; // Variable to get the value of the function.
int wCount1; // same
int wCount2; // same
int wCount3; // same

/* Input file path */
printf ( "Enter file path: " );
scanf ( "%s", path );

/* Try to open file */
fptr = fopen ( path, "r" );

/* Exit if file not opened successfully */
if ( fptr == NULL )
{
printf ( "Unable to open file.\n" ); //Error msg
printf ( "Please check you have read/write previleges.\n" ); //Help msg

exit(EXIT_FAILURE); //end
}

// Call function to count all occurrence of word
wCount = CountOccurrences ( fptr, word );
//rewind so I can use It again

rewind ( fptr );
printf ( "'%s' is found %d times in file.\n", word, wCount );

//the method is the same for all the 4 functions
fclose ( fptr ); //close file

return 0; /* How can I search for overlapping words in a txt file with the goal to differentiate from each other in a txt file */
}

//Returns total occurrences of a word in given file.
int CountOccurrences(FILE *fptr, char *word) {

char str [BUFFER_SIZE]; //The other functions are the same
char *pos;

int index, count;

//make a variable to count the amount of occurrences

count = 0;

// Read line from file till end of file.
while ((fgets(str, BUFFER_SIZE, fptr)) != NULL)
{
index = 0; //to store the word

// Find next occurrence of word in str
while ((pos = strstr(str + index, word)) != NULL)
{
index = (pos - str) + 1;

// Index of word in str is
// Memory address of pos - memory
// address of str.

count++; // sums every time for a specific word
}
}
return count;
}

最佳答案

在下面的 while 循环中的 CountOccurances() 函数中,对 word1、word2、word3 和 word4 分别使用 strcmp(),可以找到单词。

  while ((pos = strstr(str + index, word))

进一步在 fgets() 函数中,换行符将在单词读取的末尾读取,这可能导致 strcmp() 失败。可以通过让单词的最后一个字符减1为null来处理

关于c - 如何计算文本文件中相互重叠的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53952845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com