c-如何在平面数组中查找字符串



我有一个结构,其中有一个存储字符串列表的平面数组,偏移量将跟踪字符串在数组中添加的起始位置。

typedef struct
{
char element[256];
int offset;
} A;
void A_append(A* a, const char *str) {
// Concatenate on the end of element.
strcat(&a->element[a->offset], str);
// Increment the offset to the new end.
a->offset += strlen(str);
}
int main() {
A a = { .element = "" };
a.offset = 0;
char string1[] = "one";
A_append(&a, string1);
char string2[] = "two";
A_append(&a, string2);
}

现在我想搜索字符串";两个";在平面数组中,然后删除字符串。

请让我知道这是否可行。如果是,那么怎么做?

您可以使用char* strstr(const char* string, const char* substring)函数在字符串中查找子字符串,例如strstr(&a->element, "two"),它将返回指向所提供字符串中第一个出现的子字符串的指针。没有内置的C函数可以自动删除子字符串,但这里给出了一个使用memmove的示例实现。

最新更新