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
#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