Sort the Characters of a string in C – Sort String in Ascending and Descending order
Program Description:
Write a Program to Sort the Characters of a string in C programming language. The program will accept a string from the user and sorts the characters of strings in Ascending order and Descending order of character ASCII Values.
We are going to look at different methods to sort the characters in a string in C. Each program will be followed by a detailed step-by-step explanation and program output. We also provided instructions for compiling and running the program using your favorite compiler.
📢 This Program is part of the C String Practice Programs series
Before going to look at the program. Let’s understand the program requirements by looking at an example input and output of the program.
Example Input and Output:
Input:
Enter a string : Howdy, How are you?
Output:
String before sorting :Howdy, How are you?(Actual string)
,?HHadeoooruwwyy
The program sorts the characters based on the ASCII Values of the Characters. You can check the ASCII Values of all characters in C in the following post.
Prerequisites:
It is recommended to know the basics of the C-Strings, C-Arrays, and Functions in C to better understand the following program.
We will look at the Two methods to Sort the characters.
- Sorting the string Ascending Order of Characters
- Sorting the string in Descending Order of Characters
We are going to use the C standard library function qsort() to sort the characters in the string.
Syntax of Qsort() function:
1 2 |
void qsort (void* string, size_t num, size_t size, Â Â Â Â Â Â Â Â Â Â Â Â int (*compare_function)(const void*,const void*)); |
- string is the string to be sorted
- num is the length of the string
- size is the size of the data type i.e character. so it will be equal to sizeof(char)
- compare_functionis a function pointer, which points to the comparison function.
Method 1: Sort the Characters in String in Ascending Order using Qsort function in C:
Sort String in Ascending Order Program Explanation:
Start the program by declaring a string to store the input string(i.e inputStr). The size of the string is equal to the SIZE constant. which is equal to 100.
Prompt the user to provide the input string and update the inputStr character array/string. We are using the gets function to read the string from the user.
Now, To sort the string character in Ascending order, We need to define a compare function.
1 2 3 |
int charCompareAsc(const void *a, const void *b) { Â Â Â Â return *(char *)a - *(char *)b; } |
This charCompareAsc function compares the values pointed by the pointer variables a and b.
The function takes two void pointers a and b as arguments. These pointers are cast to char pointers and dereferenced in order to access the characters they point to.
The function returns the difference between the two characters, *(char *)a - *(char *)b, which will be
- A Negative value if *a is less than *b. We are checking the ASCII Values of the character here.
- A Positive value if *a is greater than *b.
- Zero if *a is equal to *b
Let’s use this compareCharAsc function with the qsort() function to sort the characters of the string in ascending order.
Program to Sort the string characters in Ascending order:
Here is the program to sort the string in Ascending order using qsort.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include <stdio.h> #include <stdlib.h> #include <string.h>  // Max Size of inputString const int SIZE = 100;  int charCompareAsc(const void *a, const void *b) {     return *(char *)a - *(char *)b; }  int main() {      // declare a inputString with 'SIZE'     char inputStr[SIZE];     int i, j;      // get the string from the user     printf("Enter a string : ");     gets(inputStr);      printf("String before sorting :%s(Actual string)\n", inputStr);      // call the 'qsort()' function with 'inputStr' and 'charCompareAsc' function     qsort(inputStr, strlen(inputStr), sizeof(char), charCompareAsc);     printf("%s\n", inputStr);     return 0; } |
Output:
Compile and Run the program using your favorite compiler
1 2 3 4 5 6 |
$ gcc sort-string.c  $ ./a.out Enter a string : Welcome String before sorting :Welcome(Actual string) Wceelmo $ |
As we can see from the above output, The program sorted the characters of the given string in Ascending order of the ASCII Values. Note that the ASCII Values of the upper case letters is smaller than the lower case letter. That is the reason the upper case W came first in the output.
Let’s look at a few more examples.
1 2 3 4 5 6 7 8 9 |
$ ./a.out Enter a string : sahara String before sorting :sahara(Actual string) aaahrs $ ./a.out Enter a string : amazon String before sorting :amazon(Actual string) aamnoz $ |
As excepted, The program is properly sorting the characters in ascending order.
Method 2: Sort the Characters in String in Descending Order using Qsort function in C Language:
Sort String in Descending Order Program Explanation:
Similar to the above program, Declare the input string ( inputStr) and Also take the user input and update the inputStr string.
Now, To sort the string character in Descending order, We need to define a compare function.
1 2 3 |
int charCompareDsc(const void *a, const void *b) { Â Â Â Â return *(char *)b - *(char *)a; } |
This charCompareDsc function compares the values pointed by the pointer variables a and b.
The function takes two void pointers a and b as arguments. These pointers are cast to char pointers and dereferenced in order to access the characters they point to.
The function returns the difference between the two characters, *(char *)b - *(char *)a, which will be
- A Positive value if *b is greater than *a. We are checking the ASCII values of the characters.
- A Negative value if *b is less than *a.
- Zero if *b is equal to *a
Let’s use this compareCharDsc function with the qsort() function to sort the characters of the string in descending order.
Program to Sort the string characters in Descending order:
Here is the program to sort the string in Descending order using qsort.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include <stdio.h> #include <stdlib.h> #include <string.h>  // Max Size of inputString const int SIZE = 100;  int charCompareDsc(const void *a, const void *b) {     return *(char *)b - *(char *)a; }  int main() {      // declare a inputString with 'SIZE'     char inputStr[SIZE];     int i, j;      // get the string from the user     printf("Enter a string : ");     gets(inputStr);      printf("String before sorting :%s(Actual string)\n", inputStr);      // call the 'qsort()' function with 'inputStr' and 'charCompareDsc' function     qsort(inputStr, strlen(inputStr), sizeof(char), charCompareDsc);     printf("%s\n", inputStr);     return 0; } |
Program Output:
Compile and Run the program
1 2 3 4 5 6 7 8 9 10 11 |
$ gcc sort-string-qsort.c $ ./a.out Enter a string : micheal String before sorting :micheal(Actual string) mliheca $ $ ./a.out Enter a string : Learn Programming Online String before sorting :Learn Programming Online(Actual string) rrronnnnmmliiggeeaaPOLÂ Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â // We have spaces at the end. $Â Â |
As we can see from the above output, The program is properly sorting the string characters in Descending order.
For example, The input string micheal characters are sorted in descending order and the resultant string is mliheca.
Related Programs:
- C Tutorials Index
- C Programs Index
- C Program to Calculate Length of the string
- C Program to Copy a String to new string
- C Program to Concatenate Two strings
- C Program to Compare Two Strings
- Count the Number of Vowels, Consonants, Digits, and Special characters in String
- C Program to Count Alphabets, Digits, Whitespaces in String
- C Program to Convert Lower case string to Upper case string
- C Program to Convert Uppercase string to Lowercase string
- C Program to Reverse a String
- C Program to Check Palindrome String
- C Program to Toggle Case of All Characters in String
- C Program to Remove Leading Whitespaces in a String
1 Response
[…] Sort String in Ascending and Descending order using Qsort() […]