C Program to Sort Word in String

This C Program Sort Word in String.

Here is source code of the C Program to Sort Word in String. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to Sort Word in String
  3.  */
  4. #include <stdio.h>
  5. #include <string.h>
  6.  
  7. void main()
  8. {
  9.     int count = 0, c = 0, i, j = 0, k, l, space = 0;
  10.     char str[100], p[50][100], str1[20], ptr1[50][100], cmp[50];
  11.  
  12.     printf("Enter the string\n");
  13.     scanf(" %[^\n]s", str);
  14.     for (i = 0;i < strlen(str);i++)
  15.     {
  16.         if ((str[i] == ' ')||(str[i] == ', ')||(str[i] == '.'))
  17.         {
  18.             space++;
  19.         }
  20.     }
  21.     for (i = 0, j = 0, k = 0;j < strlen(str);j++)
  22.     {
  23.         if ((str[j] == ' ')||(str[j] == 44)||(str[j] == 46))  
  24.         {    
  25.             p[i][k] = '\0';
  26.             i++;
  27.             k = 0;
  28.         }        
  29.         else
  30.              p[i][k++] = str[j];
  31.     }
  32.     for (i = 0;i < space;i++)    //loop for sorting
  33.     {
  34.         for (j = i + 1;j <= space;j++)
  35.         {
  36.             if ((strcmp(p[i], p[j]) > 0))
  37.             {
  38.                 strcpy(cmp, p[i]);
  39.                 strcpy(p[i], p[j]);
  40.                 strcpy(p[j], cmp);
  41.             }
  42.         }
  43.     }
  44.     printf("After sorting string is \n");
  45.     for (i = 0;i <= space;i++)
  46.     {
  47.         printf("%s ", p[i]);
  48.     }
  49. }

$ cc string18.c
$ a.out
Enter the string
welcome to sanfoundry's c programming class, welcome to c class again
After sorting string is
again c c class class programming sanfoundry's to to welcome welcome

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at programming examples on all topics, go to C Programming Examples.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.