C - Как получить слово в строке после конкретного слова? - PullRequest
0 голосов
/ 16 мая 2019

Мне нужна функция или API, чтобы получить слово после определенного слова и сохранить его в строке в C?
Например:

char str[] = "This is a sample sentence for demo";
char x[10];

Теперь мне нужно сохранить слово между "sample" и "for" (т.е. предложение) в строке x. Как я могу это сделать?

Ответы [ 2 ]

1 голос
/ 16 мая 2019

Как получить слово в строке после определенного слова?

Шаг 1, найдите позицию "sample" в str.

const char *pos = strstr(str, "sample");

Шаг 2: сканирование оттуда в поисках следующего «слова»

char x[10];
//                      v-v--------- "sample"
//                          v-v----- Next word
if (pos && sscanf(pos, "%*s %9s", x) == 1) {
  printf("Success <%s>\n", x);
} else {
  printf("Key or following word not found\n", x);
}
1 голос
/ 16 мая 2019
#include <stddef.h>  // size_t
#include <stdlib.h>  // EXIT_FAILURE
#include <ctype.h>   // isspace()
#include <string.h>  // strlen(), strstr(), sscanf()
#include <stdio.h>   // printf(), fprintf()

int main(void)
{
    char const *str = "This is a sample sentence for demo";
    char const *needle = "sample";
    size_t needle_length = strlen(needle);
    char const *needle_pos = strstr(str, needle);

    // not found, at end of str or not preceded and followed by whitespace:
    if (!needle_pos || !needle_pos[needle_length] || !isspace((char unsigned)needle_pos[needle_length]) ||
        needle_pos != str && !isspace((char unsigned)needle_pos[-1]))
    {
        fprintf(stderr, "\"%s\" couldn't be found. :(\n\n", needle);
        return EXIT_FAILURE;
    }   

    // extract the word following the word at needle_pos:
    char word[100];
    sscanf(needle_pos + needle_length, "%99s", word);
    printf("Found \"%s\" after \"%s\"\n\n", word, needle);
}
...