This blog is under construction

Monday 15 July 2013

C program to sort characters of a string in ascending order

Write a C program to sort characters of a string in ascending order.


  #include <stdio.h>
  #include <string.h>

  int main() {
        char string[256];
        int i, j, tmpChar;

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(string, 256, stdin);
        string[strlen(string) - 1] = '\0';

        /* sort the characters of a string in ascending order */
        for (i = 0; i < strlen(string) - 1; i++) {
                tmpChar = string[i];
                for (j = i + 1; j < strlen(string); j++) {
                        if (tmpChar > string[j]) {
                                tmpChar = string[j];
                                string[j] = string[i];
                                string[i] = tmpChar;
                        }
                }
        }

        /* Resultant output string */
        printf("Sorted Output String: %s\n", string);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:Engineer 
  Sorted Output String: Eeeginnr


No comments:

Post a Comment