设long_text
、keyword1
和keyword2
为三个char*
指针。 _keyword1_
和_keyword2_
是long_text
的两个子字符串。使用 strstr(long_text, keyword1)
我可以获得一个 char*
,它指向 long_text
中第一次出现的 keyword1
>,并使用 strstr(long_text, keyword2)
我可以获得一个 char*
,它指向 long_text 中第一次出现的
。 keyword2
keyword1
和 keyword2
不重叠。
有没有办法使用两个 char*
从 strstr()
获得?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
char* long_text = "this is keyword1 and this is keyword2 in long_text";
char* keyword1 = "keyword1";
char* keyword2 = "keyword2";
char* k1_start = strstr(long_text, keyword1);
char* k2_start = strstr(long_text, keyword2);
// TODO Be able to print " and this is "
return 0;
}
最佳答案
这是你遗漏的部分
// Move k1_start to end of keyword1
k1_start += strlen(keyword1);
// Copy text from k1_start to k2_start
char sub_string[32];
int len = k2_start - k1_start;
strncpy(sub_string, k1_start, len);
// Be sure to terminate the string
sub_string[len] = '\0';
关于c++ - 使用在 C 字符串中定位的两个 char* 获取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44185042/