C - 找一个单词并获得接下来的两个

时间:2016-11-09 14:45:20

标签: c string char

我正在逐行解析C中的文件。以下是我要做的事情的例子:

我有一行例如: word word word WORDTOFIND: word1 word2 word word

我想要做的是:当我找到单词WORDTOFIND时,获取该行的两个下一个单词(在这种情况下为word1word2)。在C中有一种简单的方法吗?我知道 strstr 函数,但在找到好的函数后,我找不到一种方法来获取接下来的两个单词word1word2

2 个答案:

答案 0 :(得分:0)

一种方法是:

int main(void)
{
    char *str = "rated rat cat bat hat";
    char *key = "rat ";
    char *pointer = NULL;
    char nwords = 2;

    if ((pointer = strstr(str, key)) != NULL)
    {
        while (*pointer != ' ') pointer++;
        while (nwords >= 0)
        {
            printf("%c", *pointer);
            if (*pointer == ' ') {
                nwords--;
            } else if (*pointer == '\0') {
                exit(0);
            }

            pointer++;
        }
    }
}

答案 1 :(得分:0)

您可以尝试这样的方法,使用strtok来解析每个空格中的单词。此代码还使用mallocrealloc为字符串数组分配空间,并在需要时增长它。

代码如下所示:

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

#define MAXCHAR 100

void exit_if_null(void *ptr, const char *msg);
char *stripped_word(char *word);

int
main(int argc, char const *argv[]) {
    FILE *filename;
    char line[MAXCHAR];
    char *word, *newword;
    char **allwords;
    int init_size = 8, count = 0, i;
    const char *key = "WORDTOFIND";

    filename = fopen("files.txt", "r");

    if (filename == NULL) {
        fprintf(stderr, "%s\n", "Error reading file!");
        exit(EXIT_FAILURE);
    }

    allwords = malloc(init_size * sizeof(*allwords));
    exit_if_null(allwords, "Initial Allocation");

    while (fgets(line, MAXCHAR, filename) != NULL) {
        word = strtok(line, " \n");

        while (word != NULL) {
            if (count == init_size) {
                init_size *= 2;
                allwords = realloc(allwords, init_size * sizeof(*allwords));
            }

            allwords[count] = malloc(strlen(word)+1);
            exit_if_null(allwords[count], "Initial Allocation");

            newword = stripped_word(word);

            strcpy(allwords[count], newword);

            count++;

            word = strtok(NULL, " \n");

            free(newword);
        }
    }

    for (i = 0; i < count; i++) {
        if (strcmp(key, allwords[i]) == 0) {
            printf("Next two words:\n");
            printf("%s\n", allwords[i+1]);
            printf("%s\n", allwords[i+2]);
        } 
        free(allwords[i]);
        allwords[i] = NULL;
    }

    free(allwords);
    allwords = NULL;

    return 0;
}

void
exit_if_null(void *ptr, const char *msg) {
    if (!ptr) {
        printf("Unexpected null pointer: %s\n", msg);
        exit(EXIT_FAILURE);
    }
}

char
*stripped_word(char *word) {
    int i, pos = 0;
    char *result;

    result = malloc(strlen(word)+1);
    exit_if_null(result, "Initial Allocation");

    for (i = 0; word[i] != '\0'; i++) {
        if (isalpha(word[i]) || isdigit(word[i])) {
            result[pos++] = word[i];
        }
    }

    result[pos] = '\0';

    return result;
}