6 ms·
Seems simple enough (formatted a little funny due to comment quirks): void condense_by_removing(char *z_terminated, char char_to_remove) { int i; int
by tmountain 16y ago
Seems simple enough (formatted a little funny due to comment quirks):
void condense_by_removing(char *z_terminated, char char_to_remove) {
int i;
int write_index = 0;
for (i = 0; i < strlen(z_terminated); i++) {
if (z_terminated[i] == char_to_remove) {
continue;
}
z_terminated[write_index] = z_terminated[i];
write_index++;
}
z_terminated[write_index] = '\0';
}
- coffeeaddicted 16y agoThe strlen would make this slow. Rather check if z_terminated[i] != 0.
- petercooper 16y agoYou don't need all that logic in there. for (i = 0; i <= strlen(z_terminated); i++) if (z_terminated[i] != char_to_remove) z_terminated[write_index++] = z_terminated[i]; That even removes the need to add the \0 later on.
- dalke 16y agoFor extra performance, use strchr to find the first char_to_remove. /* Find the first character to remove */ /* This doubles the performance when there are no remove characters, I assume because it uses a builtin and because I don't do unneeded writes. */ src = strchr(z_terminated, char_to_remove); if (src == NULL) return; /* src is the position in the old string, with the possible characters to remove. dest is the end position of the new string, where non-removed characters are added */ dest = src++; for (;;) { /* Skip additional remove characters */ while (*src == char_to_remove) src++; /* Copy (including copying the terminal NUL) */ if (! (*dest++ = *src++)) { /* copied a NUL - end of string */ break; } }
- deleted 16y ago[deleted]
- what 16y agoHow does that solution compare to something like this? char *copy_to = z_terminated; while(1) { if(*z_terminated == char_to_remove) z_terminated++; else if((*copy_to++ = *z_terminated++) == '\0') break; } Yeah, I know, it will break if char_to_remove is the zero-terminator or z_terminated is NULL.