Home » C solved programs » Advance C programs

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.

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





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.