Your code has multiple issues:
the loop for (int i = 0; i <= strlen(str); i++)
is very inefficient as the length of str
is recomputed at each iteration of the loop. You should simply write:
for (int i = 0; str[i] != ''; i++)
when you skip the matched substring, the character after it is copied and i
is incremented in the loop so the next occurrence is not tested correctly.
the code to append a single character is inefficient: instead of strncat(new, &ch, 1);
you should have a pointer to the end of the destination string and write *p++ = str[i];
and set the null terminator after the end of the loop.
Here is a modified version:
#include <string.h>
// remove all occurrences of sub in str into destination buffer new
// return a pointer to the destination string
char *removeSub(cont char *str, const char *sub, char *new) {
char *p = new;
size_t len = strlen(sub);
if (len > 0) {
const char *subp;
while ((subp = strstr(str, sub)) != NULL) {
memcpy(p, str, sub - str);
p += sub - str;
str = sub + len;
}
}
strcpy(p, str);
return new;
}
And an alternative without library calls:
// remove all occurrences of sub in str into destination buffer new
// return a pointer to the destination string
char *removeSub(cont char *str, const char *sub, char *new) {
char *p = new;
while (*str) {
if (*str == *sub) { /* potential substring match */
for (size_t i = 1;; i++) {
if (sub[i] == '') { /* substring match */
str += i;
break;
}
if (str[i] != sub[i]) {
*p++ = *str++;
break;
}
}
} else {
*p++ = *str++;
}
}
*p = '';
return new;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…