Vinay
Vinay

Reputation: 93

Need to write a C Program to remove repeated characters adjacent to each other

I need to remove only the repeated characters that are adjacent to each other.

Example: if the input is "heeellooo wooorllldd", the output should be "helo world". The output I am currently getting is "helo wrd".

This is the code i have.

#include <stdio.h>
#include <string.h>

main()
{
    char str[]="heeello wooorld";
    redundant(str);
}

void redundant(char *str)
{
    int check=0;
    int i,j;
    char ch;

    while(str[check]) 
    {
        ch = str[check];
        i = j = check + 1;

        while(str[i]) 
        {
            if(str[i] != ch) 
            {
                str[j] = str[i];
                j++; 
            }

            i++; 
        }

        str[j]='\0';
        check++;
    }

    printf("String after removing duplicates : %s\n",str);
} 

Upvotes: 0

Views: 1190

Answers (2)

Sourav Kanta
Sourav Kanta

Reputation: 2757

Whats happening is that your in code a character is taken and then the entire string is checked if the same character is present again .If it is present it is deleted .Therefore your program has only one copy of each character instead of deleting adjacent same characters.

Try this code instead :

#include<stdio.h>    
#include<string.h>
#include <stdio.h>
 #include <conio.h>
void redundant(char *);
main()
{
 clrscr();
 char str[]="heeello wooorld";
 redundant(str);
 getch();
 }

void redundant(char *str)
  {
 int check=0;
 int i,j;
 char ch;
 while(str[check]) {
 j=i=check;
 ch= str[check+1];
 if(str[check] == ch)
   {
    i++;
   check--;
    }
 while(str[i]) {
 str[j] = str[i];
 j++;
 i++;
 }
 str[j]='\0';   
 check++;
 }
 printf("String after removing duplicates : %s\n",str);
}

In my code i check if the adjacent character is same or not.If yes I copy the entire string from the next to next position instead.

You could have shortened code by using strcat function as shown :

void redundant(char *str)
  {
  int check=0;
  while(str[check]) {
  if(str[check] == str[check+1])
    {
     str[check+1]='\0';
     strcat(str,str+check+2);
     check--;
     }
     check++;
   }

Upvotes: 2

dlask
dlask

Reputation: 8982

I was looking for a minimalistic solution. Just for fun.

void redundant(char *str) {
    int lastch = -1;         /* last read character */
    char* inpp = str;        /* pointer to input location */
    char* outp = str;        /* pointer to output location */
    while (*inpp != '\0') {
        if (*inpp != lastch) {
            *outp++ = lastch = *inpp;
        }
        inpp++;
    }
    *outp = '\0';
    printf("String after removing duplicates : %s\n", str);
}  

Upvotes: 3

Related Questions