TutorialStudyMite

Program to sort a string in C

PPooja Rao2 min read
Beginner friendly

Track completion, mastery, and revision.

Understanding Character Sorting

When sorting characters in a string alphabetically, it's important to understand that computers use ASCII values rather than traditional alphabetical order. Key points to note:

  • Case Sensitivity: 'A' and 'a' are treated as different characters

  • ASCII Order: Uppercase letters (A-Z) have lower ASCII values than lowercase letters (a-z)

  • Special Characters: Punctuation, numbers, and symbols appear before letters in ASCII order

ASCII Order Hierarchy:

Special characters/numbers → Uppercase letters → Lowercase letters

Approach 1: Manual Sorting without String Functions

Algorithm

1. Read input string from user

2. Calculate string length (excluding null terminator)

3. Use nested loops to compare adjacent characters

4. Swap characters if they're out of order

5. Continue until the entire string is sorted

Implementation


#include <stdio.h>
#include <stdlib.h>

int main() {
    char temp, *str;
    int i, j, length, size = 100;

    printf("Enter the string to be sorted: ");

    str = (char*)malloc(size);
    length = getline(&str, &size, stdin);
    length--;  // Exclude newline character from length

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

    // Bubble sort implementation

    for (i = 0; i < length - 1; i++) {
        for (j = i + 1; j < length; j++) {
            if (str[i] > str[j]) {
                // Swap characters
                temp = str[i];
                str[i] = str[j];
                str[j] = temp;
            }
        }
    }

    printf("String after sorting: %s\n", str);
    free(str);  // Free allocated memory
    return 0;
}

Sample Outputs

Example 1: Mixed characters


Enter the string to be sorted: How you doing ?

String before sorting: How you doing ?

String after sorting:    ?Hdginooouwy

Example 2: Uppercase only


Enter the string to be sorted: BACDE

String before sorting: BACDE

String after sorting: ABCDE

Key Points

  • Memory Management: Uses malloc() for dynamic memory allocation and free() to release memory

  • Input Handling: getline() safely handles input of any length

  • Sorting Algorithm: Implements bubble sort with O(n²) time complexity

  • Case Sensitivity: Maintains the original case of characters during sorting

Alternative Approaches

For better performance with larger strings, consider:

  • Using built-in sorting functions like qsort()

  • Implementing more efficient algorithms (quick sort, merge sort)

  • Using case-insensitive comparison if needed


Note: This implementation preserves the original character cases. For case-insensitive sorting, additional character conversion would be required before comparison.

Learn C Programming

Finished reading?

Was this helpful?

Your feedback shapes better tutorials for everyone.