C - 如何在特定单词之后获取字符串中的单词?
C - How to get a word in a string after a particular word?
我需要一个函数或 API 来获取特定单词后的单词并将其存储在 C 中的字符串中?
例如:
char str[] = "This is a sample sentence for demo";
char x[10];
现在我需要将 "sample"
和 "for"
之间的单词(即句子)存储在字符串 x
中。我该怎么做?
#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);
}
How to get a word in a string after a particular word?
第一步,找到"sample"
在str
中的位置。
const char *pos = strstr(str, "sample");
第 2 步:从那里扫描寻找下一个 "word"
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);
}
我需要一个函数或 API 来获取特定单词后的单词并将其存储在 C 中的字符串中?
例如:
char str[] = "This is a sample sentence for demo";
char x[10];
现在我需要将 "sample"
和 "for"
之间的单词(即句子)存储在字符串 x
中。我该怎么做?
#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);
}
How to get a word in a string after a particular word?
第一步,找到"sample"
在str
中的位置。
const char *pos = strstr(str, "sample");
第 2 步:从那里扫描寻找下一个 "word"
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);
}