Remove every repeated occurrence of a character from a string in place (keeping the first), shifting the rest left with memmove and searching with strchr.
Solution
main.c
#include <stdio.h>
#include <string.h>
static void dedupe(char *s) {
for (size_t i = 0; s[i]; i++) {
char *dup;
while ((dup = strchr(s + i + 1, s[i])) != NULL)
memmove(dup, dup + 1, strlen(dup + 1) + 1); /* +1 moves the '\0' too */
}
}
int main(void) {
char a[] = "programming", b[] = "mississippi";
dedupe(a);
dedupe(b);
printf("%s %s\n", a, b);
return 0;
}
Output Verified by compiling and running
progamin misp
The source and destination of each shift overlap, so memmove is required. strchr starting after position i finds the next duplicate of s[i].
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!