Showing posts with label Group all occurrences of characters according to first appearance. Show all posts
Showing posts with label Group all occurrences of characters according to first appearance. Show all posts

Friday, 14 April 2017

Group all occurrences of characters according to first appearance: C Program

Given a string of lowercase characters, the task is to print the string in a manner such that a character comes first in string displays first with all its occurrences in string.
Examples:
Input :  str = "occurrence"
output : occcurreen 

Input  : str = "cdab"
Output : cdab



C Program

#include <stdio.h>
#include <string.h>
main()
{
char st[100],temp,s[100];
int i,k=0,j,flag=0;
gets(st);
               
for(i=0;st[i]!='\0';i++)
{
                for(j=i;st[j]!='\0';j++)
                {
                                if(k<strlen(st))
                                {
                                                if(st[i] == st[j])
                                                                s[k++]=st[j];      
                                }
                                else
                                {
                                                flag=1;
                                                break;
                                }                                             
                }
                if(flag ==1)
                                break;
}
s[k]='\0';
puts(s);
}