C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Sort characters in string

C Program: Sort characters in string

C

#include <stdio.h>

#include <string.h>

 

int main() {

    char str[200], temp;

    int i, j, len;

 

    // Input string

    printf("Enter a string: ");

    fgets(str, sizeof(str), stdin);

 

    // Remove newline character if present

    str[strcspn(str, "\n")] = '\0';

 

    len = strlen(str);

 

    // Sort characters using simple bubble sort

    for (i = 0; i < len - 1; i++) {

        for (j = i + 1; j < len; j++) {

            if (str[i] > str[j]) {

                temp = str[i];

                str[i] = str[j];

                str[j] = temp;

            }

        }

    }

 

    printf("String after sorting characters: %s\n", str);

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter a string: itdeveloper
String after sorting characters: deeiloprtv

OUTPUT 2 :
Enter a string: C Language
String after sorting characters:  CLaagenu

Explanation

  • The program uses bubble sort logic to rearrange characters in ascending (alphabetical) order based on their ASCII values.
  • It ignores newline characters and sorts all characters including uppercase, lowercase, digits, and symbols.
  • Note: Uppercase letters (A–Z) have lower ASCII values than lowercase (a–z), so they appear first.