Program to sort a string in C
Written by
Sort characters in a string in alphabetical order
We have to sort the characters of the string in an alphabetical order. Note that unlike our traditional alphabets, in computer’s memory the characters are recognised by their ASCII values. Hence, ‘A’ and ‘a’ are different. Also, the ASCII value of ‘A’ is smaller than ‘a’ hence, ‘A’ will be occupying first position followed by ‘a’ if they are just the constituent characters of the string. Special characters like ‘?’ ,”, ‘#’ etc and numbers also come prior to the alphabets in order of their ASCII values.
Refer ASCII table for the same.
APPROACH 1: Without using string functions:
- We scan the input from the user.
- Since we are using getline function, it returns the number of blocks read which is one greater than the length of string ; as the last character is newline character.
- If using an alternate method to scan input then you have to use a loop to increment a counter till the ‘\0’ character is encountered. Refer length of string program for various techniques.
- Two loops are used, one for the ith character and the next for the i+1 th character as we have to compare the adjacent characters in order to decide to swap them or not.
- We use a variable of type character here – temp , in order to store the character at ith place if a swap has to be performed in order to sort string alphabetically.
Code:
#include <stdio.h>
#include <string.h>
int main ()
{
char temp, *str;
int i, j, l, size = 100;
printf("Enter the string to be sorted: ");
str = (char*)malloc(size);
l = getline(&str, &size, stdin);
l--; //length of string is no of blocks read - 1
printf("String before sorting: %s \n", str);
for (i = 0; i < l-1; i++)
{
for (j = i+1; j < l; j++)
{
if (str[i] > str[j])
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
printf("String after sorting: %s \n", str);
return 0;
}
Output:
Enter the string to be sorted: How you doing ? (mixture of uppercase, lowercase and special characters)
String before sorting: How you doing ?
String after sorting: ?Hdginooouwy
Enter the string to be sorted: BACDE (all are uppercase characters)
String before sorting: BACDE
String after sorting: ABCDE