Skip to main content

Rewrite string characters alphabetically

Short answer

Compare each character with later ones; if a later character has a smaller ASCII value, swap them. After sorting all pairs, the characters appear in ascending alphabetical order.

Write a program to read a string and rewrite its characters in alphabetical order.

Logic. Every character of the string is compared with the characters after it (a simple exchange sort). Whenever a later character has a smaller ASCII value, the two are swapped. After the loops the characters are in ascending order. For mixed upper and lower case letters, convert the string to one case first (tolower), because capital letters have smaller ASCII codes than small letters.

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

int main(void)
{
    char s[100], t;
    printf("Enter a string: ");
    scanf("%99s", s);
    int n = strlen(s);

    for (int i = 0; i < n - 1; i++)
        for (int j = i + 1; j < n; j++)
            if (s[i] > s[j]) {             /* swap to keep smaller first */
                t = s[i];
                s[i] = s[j];
                s[j] = t;
            }
    printf("Characters in alphabetical order: %s\n", s);
    return 0;
}

Sample run

Input: computer

Enter a string: Characters in alphabetical order: cemoprtu

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 7 questions →