In this tutorial, we will write a c program to sort a string array in ascending order. Before that, you may go through the following topics in C
C Program to sort a String in Ascending order
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include <stdio.h> #include <string.h> #define MAX_size 100 //maxiimum size of the string void main() { char str[MAX_size], ch; int i, j, length; printf("Enter the string: "); fgets(str, sizeof str, stdin); length = strlen(str); for (i = 1; i < length; i++) { for (j = 0; j < length - i; j++) { if (str[j] > str[j + 1]) { ch = str[j]; str[j] = str[j + 1]; str[j + 1] = ch; } } } printf("\nAfter sorting, the string appears: %s", str); } |
Output:
Enter the string: programs
After sorting, the string appears:
agmoprrs