gpt4 book ai didi

c - 如何在 C 中的两个子字符串之间找到第 n 个子字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 04:17:55 25 4
gpt4 key购买 nike

我正在使用此函数获取两个子字符串之间的子字符串。

char * extract_between(const char *str, const char *p1, const char *p2/*, const int instance*/)
{
//int count;
const char *i1 = strstr(str, p1);
/*for (count = 0; ; ++count) {
const char *i1 = strstr(str, p1);
if (count==instance)
break;
}*/
if(i1 != NULL)
{
const size_t pl1 = strlen(p1);
const char *i2 = strstr(i1 + pl1, p2);
if(p2 != NULL)
{
/* Found both markers, extract text. */
const size_t mlen = i2 - (i1 + pl1);
char *ret = malloc(mlen + 1);
if(ret != NULL)
{
memcpy(ret, i1 + pl1, mlen);
ret[mlen] = '\0';
return ret;
}
}
}
return 0;
}

我想修改它,以便它本身搜索子字符串的第 n 个实例。这怎么可能?我试过 for(count) 但我不确定如何格式化它。

最佳答案

这对你有用吗?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char*
extract_between (const char* str, const char* p1, const char* p2, int instance)
{
int count = -1;
const char* i1 = str - 1;
for (; count < instance; ++count) {
i1 = strstr(i1 + 1, p1);
if (i1 == NULL)
return NULL;
}
const size_t pl1 = strlen(p1);
const char* i2 = strstr(i1 + pl1, p2);
if (i2 != NULL)
{
/* Found both markers, extract text. */
const size_t mlen = i2 - (i1 + pl1);
char* ret = malloc(mlen + 1);
if (ret != NULL)
{
memcpy(ret, i1 + pl1, mlen);
ret[mlen] = '\0';
return ret;
}
}
return NULL;
}

样本运行:

extract_between("foobarbaz", "foo", "bar", 0) = ""
extract_between("foobarbaz", "foo", "bar", 1) = NULL
extract_between("foobarbaz", "foo", "baz", 0) = "bar"
extract_between("foobarfoobarbaz", "foo", "bar", 1) = ""
extract_between("foobarfoobarbaz", "foo", "baz", 1) = "bar"
extract_between("foofoofoobarfoo", "foo", "bar", 2) = ""
extract_between("foofoofoobarfoo", "foo", "foo", 2) = "bar"
extract_between("foofoofoobarfoo", "foo", "bar", 3) = NULL

关于c - 如何在 C 中的两个子字符串之间找到第 n 个子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49744473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com