LearnFrenzy
Sign in Take a free test

C Library Functions · Library Function Programs · Question 8

Remove repeated characters from a string with memmove in C Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

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].

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links