C Program to Sort Characters of a String

Write a program in c to sort characters of a string in alphabetical order

Given a string, we have to sort characters of the string in alphabetical order. We will sort the characters of string on the basis of ASCII value of characters.

For Example
If input string is "TECHCRASHCOURSE"
Output string should be "ACCCEEHHORRSSTU"

C program to sort the characters of a string by counting character frequency

In this program, we are going to use counting sort algorithm which sorts numbers in given range in linear time. This algorithm uses an extra array to count the frequency of each character of string. We first take a string as input from user using gets function. Then it calls a user defined function 'sortString' that takes input and output array as input and stores the sorted array in output array. Function sortString count the frequency of characters and store it in counterArray integer array. We populate the outputArray in alphabetical order based on the character's frequency in counterArray. At last we add a null character at the end of outputArray.

* C Program to sort characters of a string
#include <stdio.h>
#include <conio.h>
#include <string.h>

void sortString(char* inputString, char* outputArray);
int main(){
    char inputString[100], outputArray[100];
    printf("Enter a String \n");
    sortString(inputString, outputArray);
    printf("Sorted string \n%s", outputArray);

    return 0;

 * Function to sort characters of a string 
void sortString(char* inputString, char* outputArray){
    /* initialize counterArray to 0 */
    int counterArray[256] ={0}, length, counter, index;
    length = strlen(inputString);
    /* Count frequency of characters in input array*/
    for(counter = 0; counter < length; counter++){
    /* Populate output array */
    for(counter = 0, index = 0; counter < 256; counter++){
        if(counterArray[counter] != 0){
            while(counterArray[counter] > 0){
                outputArray[index++] = counter;
    outputArray[index] = '\0';
Program Output
Enter a String
Sorted string
Enter a String
Sorted string

Related Topics
C program to compare two strings
C program to concatenate strings
C program to check string is palindrome
C program to remove vowels from a string
C program to remove extra spaces from string
C Program to find frequency of characters in a string
C program to convert lowercase string to uppercase
List of all C programs