Sort characters of a string
C program to sort characters of the string in lexicographical order (dictionary order).
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 50
void sort_str(char str[MAX])
{
int freq[26] = {0};
int i, j;
for(i=0;i<strlen(str);i++)
{
freq[str[i] - 'a']++;
}
printf("\nSorted string\t:");
for(i=0;i<26;i++)
{
for(j=0;j<freq[i];j++)
{
printf("%c",'a'+i);
}
}
}
void main()
{
char str[MAX];
printf("Enter first string\t:");
gets(str);
sort_str(str);
getch();
}
Output
Enter first string :coursecrux
Sorted string :cceorrsuux