我正在编写一个C程序,其中读取两个文件:file1.txt是一个大文本文件(例如一本小说),另一个file2.txt是一个单词列表。到目前为止,我的程序逐行扫描整个文件,搜索每个单词。现在我需要一种方法来存储每个单词的每个实例出现的行号。
例如,假设 file2.txt 包含两个单词“apple”和“pear”。我现在需要我的程序创建两组数据,存储每个单词出现在 file1.txt 中的行号。
我想到的一个解决方案是为 file2.txt 中的每个单词创建一个数组,这些数组的每个元素都是行号:
apple[5] = {6, 12, 28, 44}
pear[3] = {10, 37}
有什么办法可以做到这一点吗?即是否可以根据 file2.txt 中的单词数量创建可变数量的数组,并且每个数组的长度根据单词出现的行数来确定?
最佳答案
一般来说,
#define MAX_WORD_LEN (50)
struct wordCount
{
int Count;
char Word[MAX_WORD_LEN];
};
struct wordCount *pWordCount = NULL;
int numWordCount = 0;
read file2 (the one containing the word list)
for each extractedWord
if word not already in list (it should not be)
realloc ( pWordCount, sizeof(struct wordCount)* (numWordCount+1) )
if realloc successful
pWordCount[numWordCount].count = 0;
memset( pWOrdCount[numWOrdCount].word, 0x00, MAX_WORD_LEN );
strncpy(pWordCount[numWordCount], extractedWord, MAX_WORD_LEN-1 )
numWordCount++;
endif
endif
end for
now you have an array of struct wordCount that you can search
for each word extracted from file1
When a word, extracted from file1 matches a word in the pWordCount array
then
pWordCount[currentIndex].count++;
关于c - 尝试找到一种方法来存储可变数量的项目的可变数量的数据(不使用链接列表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30008451/