下面是一种方法。相反到位删除字符和洗牌剩余的字符(这是一种痛苦),你复制你想要保留另一个数组中的字符:
#include <string.h>
...
void removeSubstr(const char *src, const char *substr, char *target)
{
/**
* Use the strstr() library function to find the beginning of
* the substring in src; if the substring is not present,
* strstr returns NULL.
*/
char *start = strstr(src, substr);
if (start)
{
/**
* Copy characters from src up to the location of the substring
*/
while (src != start) *target++ = *src++;
/**
* Skip over the substring
*/
src += strlen(substr);
}
/**
* Copy the remaining characters to the target, including 0 terminator
*/
while ((*target++ = *src++))
; // empty loop body;
}
int main(void)
{
char *src = "This is NOT a test";
char *sub = "NOT ";
char result[20];
removeSubstr(src, sub, result);
printf("Src: \"%s\", Substr: \"%s\", Result: \"%s\"\n", src, sub, result);
return 0;
}
你能更改标题?你不是在讨论用户输入事件......也许就像“如何从C中的字符串中删除子字符串?” – andrewmu 2010-10-28 16:29:58
这不起作用,您需要for循环或memmove。就复杂性而言,它必须是O(n)。 – 2010-10-28 16:38:28
@andrewmu ok,根据你的建议更改 – noor 2010-10-28 16:38:31