C-如何在特定单词之后获取字符串中的单词?

时间:2019-05-16 04:48:46

标签: c c-strings

我需要一个函数或API在特定单词之后获取一个单词并将其存储在C语言的字符串中吗?
例如:

'a b c d e f g h i j k l'

现在,我需要将char str[] = "This is a sample sentence for demo"; char x[10]; "sample"之间的单词(即句子)存储在字符串"for"中。我该怎么办?

2 个答案:

答案 0 :(得分:1)

#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);
}

答案 1 :(得分:1)

  

如何在特定单词之后获取字符串中的单词?

第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);
}