c - 尝试找到一种方法来存储可变数量的项目的可变数量的数据(不使用链接列表)

标签 c arrays list

我正在编写一个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/

相关文章:

c - 正则表达式与管道在速度方面的比较

c - 如何找到矿山中最大数量的钻石?

单个类类型的 C# 数组或列表

c# - 从列表集合中删除项目不删除

将 8 位 int 转换为 32 位

C++:如何使用名称长度从内存中的字符指针中取消引用多个字符

c - 从用户输入读取数组的函数产生垃圾值

arrays - React-native Sqlite,强制 ListView 用新数据更新

python - 为什么 list 会询问 __len__?

python - 复制列表错误Python(康威生命游戏的一部分)