将.txt文件拆分为单词并将每个单词存储在数组中

时间:2016-12-11 22:11:36

标签: c arrays string

让我们说我的文件有大约1000个单词,包括逗号,点和分号。 我必须将文本分成单词(可能使用" strtok",但我不知道如何正确地执行此操作)然后将这些单词写入数组。怎么做这样的事情?有人可以写一段工作代码并解释它是如何工作的吗?

1 个答案:

答案 0 :(得分:1)

我希望这个程序可以帮到你。它可能不完美,但它接近你的要求。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main()
{
    char str[5000];
    char *ptr;
    char *words[5000];
    FILE * fp = fopen("hi.txt", "r");
    fgets(str, 49, fp);             // read 49 characters
    ptr = strtok(str, ",.; ");         // split our findings around the " "
    int i = 0;
    while(ptr != NULL)  // while there's more to the string
    {
        words[i]= ptr;
        i++;
        ptr = strtok(NULL, ",.; "); // and keep splitting
    }
    fclose(fp);

    for(int j=0;j<i;j++) {
        printf("%s\n", words[j]);
    }
}

档案hi.txt

foo, bar. baz; bletch. 

测试

./a.out
foo
bar
baz
bletch
相关问题