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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.