Python,C,C++ and JAVA programs for CBSE, ISC, B.Tech and I.T Computer Science and MCA students

The Programming Project: Sorting of words in a String : C Code

Saturday, December 15, 2012

Sorting of words in a String : C Code


Program to sort the words of a string

/* To sort the words of an input string */
#include<stdio.h>
#include<string.h>
#include<malloc.h>
int main()
{
char str[40],*x[10],*temp;
int i=0,j=0,len,t,k,l,tmp;
printf("\n Enter a string:");
gets(str);
len=strlen(str);
for(i=0;i<=len;i++)
      {
      k=i;
      tmp=0;
      while(str[k]!=' ' && str[k]!='\0')
            {
            k++;
            tmp++;
            if(str[i]=='\n')
            break;
            }
            x[j]=(char *)malloc(tmp*sizeof(char));
            l=0;
                  for(t=i;t<tmp+i;t++)
                  {
                        *(x[j]+l)=str[t];
                        l++;
                  }
                  *(x[j]+l)='\0';
            i=k;
            j++;
            }
for(i=0;i<j-1;i++)
      {
            for(k=i+1;k<j;k++)
                  {
                  if(strcmp(x[i],x[k])>0)
                        {
                        temp=x[k];
                        x[k]=x[i];
                        x[i]=temp;
                        }
                  }
      }
puts("\n Sorted words of the string:\n");
for(i=0;i<j;i++)
      printf("%s\n",x[i]);
return 0;
}



Input/Output:

Enter a string:sorting of the words in a string

 Sorted words of the string:

a
in
of
sorting
string
the
words


No comments:

Post a Comment