C Program to Sort a String by User Input

Sorting a string in C involves arranging its characters in either ascending or descending order based on their ASCII values. Here’s a simple program to sort a string in ascending order

Program :

#include <stdio.h>
#include <string.h>
int main ()
{
char str[100], chTemp;
char temp;
int i, j,len;
printf(“C Program to sort character in descending order\n”);
printf(“Please enter the string : “);
scanf(“%s”,str);
len = strlen(str);
for(i=0; i<len; i++){
for(j=0; j<(len-1); j++){
if(str[j]>str[j+1]){
chTemp = str[j];
str[j] = str[j+1];
str[j+1] = chTemp;
}
}
}
printf(“\nSame string in ascending order: %s\n”, str);

for (i = 0; i < len-1; i++) {
for (j = i+1; j < len; j++) {
if (str[i]< str[j]) {
temp = str[j];
str[j] = str[i];
str[i] = temp;
}
}
}
printf(“After sorting character in descending order : %s”, str);
return 0;
}

Output :

Leave a Comment

Your email address will not be published.

Shopping Basket
Verified by MonsterInsights