C program to sort repeated words in string

Program Description

The program accept a String S containing multiple words as the input. The program must find the words which are repeated more than once in the string S. Then the program must sort the repeated words in descending order based on the length. If two or more words have same length the program must sort those words in the order of their occurrence. If all the words in the string S are unique then program must print -1 as output. 


#include<stdio.h>

#include <stdlib.h>

#include<string.h>

int main()

{

char s[1001],s1[1001][1001],s2[1001][1001],s3[1001][1001],t1[1000];

scanf("%[^\n]s",s);

int i,j=0,k=0,l,m,n,o,z=0,t,x,a[1000],count=0;

for(i=0;i<strlen(s);i++)

{

    if(s[i]==' ')

    {

        s1[j][k]='\0';

        s2[j][k]='\0';

        j++;

        k=0;

    }

    else

    {

        s1[j][k]=s[i];

        s2[j][k]=s[i];

        k++;

    }

}

s1[j][k]='\0';

s2[j][k]='\0';

j++;

x=j;

for(l=0;l<j;l++)

{

    for(m=l+1;m<j;)

    {

        if(strcmp(s1[l],s1[m])==0)

        {

            for(o=m;o<j;o++)

            {

                strcpy(s1[o],s1[o+1]);

            }

            j--;

        }

        else

        m++;

    }

}

for(i=0;i<j;i++)

{

    count=0;

    for(k=0;k<x;k++)

    {

        if(strcmp(s1[i],s2[k])==0)

        {

            count++;

        }

    }

    if(count>1)

    {

        a[z]=strlen(s1[i]);

        strcpy(s3[z],s1[i]);

        z++;

    }

}

for(i=0;i<z;i++)

{

    for(k=i+1;k<z;k++)

    {

        if(a[i]<a[k])

        {

            t=a[i];

            a[i]=a[k];

            a[k]=t;

            strcpy(t1,s3[i]);

            strcpy(s3[i],s3[k]);

            strcpy(s3[k],t1);

        }

    }

}

if(z!=0)

{

for(i=0;i<z;i++)

{

    printf("%s ",s3[i]);

}

}

else

printf("-1");

}


Input 1

when there is a will there is a way

Output 1

there is a

Input 2

Adversity and loss makes a man wise

Output 2

-1

Input 3

If You are not part of the solution you are part of the problem

Output 3

part are the of 

Rajesh

This Blog will help you to find out the c programs solution easily and also you can able to understand the program.Please follow our blog for more useful updates.

Post a Comment (0)
Previous Post Next Post