-1

How can I replace multiple consecutive occurences of a character with a single occurrence in C?

For example, if I have a char myString[]="??hello?world????" I would like to have the output as ?hello?world?.

I found this link but it replaces a specific pattern. However, what if there are variable number of repeating characters?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
hw-135
  • 162
  • 1
  • 15
  • 1
    What have you tried, and how did it fail? – Quentin Nov 08 '19 at 16:37
  • Please refresh [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). And please try to create a [mcve] of your attempt to show us, describing the problems you have with it. – Some programmer dude Nov 08 '19 at 16:43
  • 2
    Would you consider 'l' as a repeating character in 'Hello'? – Lily AB Nov 08 '19 at 16:52

2 Answers2

3

It can be done using one loop.

Here you are.

#include <stdio.h>

char *remove_duplicates(char *s, char c) {
    for (char *p = s, *q = s; *q;) {
        if (*++q != c || *p != c)
            *++p = *q;
    }
    
    return s;
}

int main(void) {
    char s[] = "??hello?world????";

    printf("\"%s\"\n", s);
    printf("\"%s\"\n", remove_duplicates(s, '?'));

    return 0;
}

The program output is

"??hello?world????"
"?hello?world?"

It is assumed that the null-terminating character should not be supplied as an argument of the function. Otherwise the function has no effect and returns the same string.

pevik
  • 4,523
  • 3
  • 33
  • 44
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Just in case additional answer "??hello?world????" -> "?helo?world?"

#include <stdio.h>
#include<string.h>
int main()
{
    char myString[]="??hello?world????";
    int i,j,length=strlen(myString);
    char res[length];
    char prev;
    for(i=0,j=0;i<=length;i++)
    {
        if(i==0)
        {
            prev=myString[i];
            res[j]=prev;
            j++;
        }
        else
        {
            if(prev!=myString[i])
            {

                res[j]=myString[i];
                prev=res[j];
                j++;
            }
        }
    }
    printf("%s",res);
    return 0;
}
Sathvik
  • 565
  • 1
  • 7
  • 17