c++ - 使用在 C 字符串中定位的两个 char* 获取子字符串

标签 c++ c string char

long_textkeyword1keyword2 为三个char* 指针。 _keyword1__keyword2_long_text 的两个子字符串。使用 strstr(long_text, keyword1) 我可以获得一个 char*,它指向 long_text 中第一次出现的 keyword1 >,并使用 strstr(long_text, keyword2) 我可以获得一个 char*,它指向 long_text 中第一次出现的 keyword2 keyword1keyword2 不重叠。

有没有办法使用两个 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/

相关文章:

c++ - Visual C++ 输出退出得如此之快

c++:为什么调用 foo(X&) 而不是 foo(X&&)?

c - 如何在 C 程序中获得 Expect 的类似功能

c - 为什么 c 中的 getch() 在我的 mac os x 上不起作用?

c - 从c中不同时出现的字符串中删除一个字符

c++ - 作用域结束后重新分配

C: undefined reference `dlopen`/`dlsym` 尽管添加了 `-ldl` 标志

python - 按前 N 个字符对字符串进行排序

python - 按字符或空格 python 拆分行

c++ - 如何检查 std::vector 超出范围的访问