Q:

C program to remove consecutive repeated characters from string

0

C program to remove consecutive repeated characters from string

This program will read a string and remove repeated consecutive characters from the string and print new updated string. In this program we will not use another string to copy string after removing the characters; we can say this program is for removing consecutive characters from the string without using another string.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Removing consecutive repeated characters from string using C program

/*C program to remove consecutive repeated characters from string.*/
 
#include <stdio.h>
 
int main()
{
 
    char str[100];
    int i,j,len,len1;
 
    /*read string*/
    printf("Enter any string: ");
    gets(str);
     
    /*calculating length*/
    for(len=0; str[len]!='\0'; len++);
 
    /*assign 0 to len1 - length of removed characters*/
    len1=0;
 
    /*Removing consecutive repeated characters from string*/
    for(i=0; i<(len-len1);)
    {
        if(str[i]==str[i+1])
        {
            /*shift all characters*/
            for(j=i;j<(len-len1);j++)
                str[j]=str[j+1];
            len1++;
        }
        else
        {
            i++;
        }
    }
 
    printf("String after removing characaters: %s\n",str);
 
    return 0;
}

Output

First Run:
Enter any string: AABBCCDD
String after removing characaters: ABCD

Second Run:
Enter any string: AAAABBBBCCCCDDDD
String after removing characaters: ABCD

Third Run:
Enter any string: AAA AAA BBB CCCC DDDD
String after removing characaters: A A B C D

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now