You are here

C program to sort a string in alphabetic order

C program to sort a string in alphabetic order: For example, if a user inputs a string "programming" then the output will be "aggimmnoprr", so output string will contain characters in alphabetical order. We assume input string contains only lower case alphabets. First, we count how many times characters 'a' to 'z' appear in input string and then create another string which contains characters 'a' to 'z' as many times as they appear in the input string.

C programming code

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. int main()
  6. {
  7.   char ch, input[100], output[100];
  8.   int no[26] = {0}, n, c, t, x;
  9.  
  10.   printf("Enter some text\n");
  11.   scanf("%s", input);
  12.  
  13.   n = strlen(input);
  14.  
  15.   /** Storing how many times characters (a to z)
  16.     appears in input string in an array */
  17.  
  18.   for (c = 0; c < n; c++)
  19.   {
  20.     ch = input[c] - 'a';
  21.     no[ch]++;
  22.   }
  23.  
  24.   t = 0;
  25.  
  26.   /** Insert characters 'a' to 'z' in output string as many times
  27.     as they appear in the input string */
  28.  
  29.   for (ch = 'a'; ch <= 'z'; ch++)
  30.   {
  31.     x = ch - 'a';
  32.  
  33.     for (c = 0; c < no[x]; c++)
  34.     {
  35.       output[t] = ch;
  36.       t++;
  37.     }
  38.   }
  39.   output[t] = '\0';
  40.  
  41.   printf("%s\n", output);
  42.  
  43.   return 0;
  44. }

Output of program:
Sort a string program output

C program using pointers

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. void sort_string(char*);
  6.  
  7. int main()
  8. {
  9.    char string[100];
  10.  
  11.    printf("Enter some text\n");
  12.    gets(string);
  13.  
  14.    sort_string(string);
  15.    printf("%s\n", string);
  16.  
  17.    return 0;
  18. }
  19.  
  20. void sort_string(char *s)
  21. {
  22.    int c, d = 0, length;
  23.    char *pointer, *result, ch;
  24.  
  25.    length = strlen(s);
  26.  
  27.    result = (char*)malloc(length+1);
  28.  
  29.    pointer = s;
  30.  
  31.    for ( ch = 'a' ; ch <= 'z' ; ch++ )
  32.    {
  33.       for ( c = 0 ; c < length ; c++ )
  34.       {
  35.          if ( *pointer == ch )
  36.          {
  37.             *(result+d) = *pointer;
  38.             d++;
  39.          }
  40.          pointer++;
  41.       }
  42.       pointer = s;
  43.    }
  44.    *(result+d) = '\0';
  45.  
  46.    strcpy(s, result);
  47.    free(result);
  48. }

Download Sort string program.