Advertisement

C Program to sort string in alphabetical order


In this program, You will learn how to sort string in alphabetical order in c.


List of unsorted string: abc, kbc, xiith, john

List of sorted string in alphabetical order: abc, bck, hiitx, jhno

Example: How to sort string in alphabetical order in c

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

int main() {
    int i, j, temp;
    char str[100];

    printf("Enter a string:");
    scanf("%[^\n]%*c", str); 

    int size = strlen(str);

    for (i = 0; i < size; i++) {
        for (j = i + 1; j < size; j++) {
            if (str[i] > str[j]) {
                temp = str[i];
                str[i] = str[j];
                str[j] = temp;
            }
        }
    }
    printf("Sorted string value:%s", str);

    return 0;
}

Output:

Enter a string:welcome to xiith
Sorted string value:  ceehiilmoottwx