codescracker
c

C Program to Sort String



« Previous Program Next Program »

Here we will learn about how to sort any given string (by user at run-time) in ascending and descending order both one by one. Let's first start with how to sort string in ascending order.

C Sort String in Ascending Order

Here we have created a program that will receive any string from the user using gets() function and then will sort the string in ascending order. For example, if the given string is codescracker, then the string after sorting in ascending order will be acccdeekorrs

// ----codescracker.com----

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
    char str[100], chTemp;
    int i, j, len;
    printf("Enter any string: ");
    gets(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:\n%s", str);
    getch();
    return 0;
}

As the program was written under Code::Blocks IDE, therefore after successful build and run, here is the sample run of the above program:

c sort string ascending order

Supply any string say codescracker and press ENTER key to see the same string with sorted its each and every character in ascending order as shown here in the following snapshot:

c program sort string in ascending order

Here are the list of some main steps used in above program:

C Sort String in Descending Order

Let's create another program in C, that will also receive any string from user and will sort the given string in descending order as shown in the program given below. For example, if the given string is codescracker, then the string after sorting in descending order will be srrokeedccca:

// ----codescracker.com----

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
    char str[100], chTemp;
    int i, j, len;
    printf("Enter any string: ");
    gets(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 descending order:\n%s", str);
    getch();
    return 0;
}

Here is the final snapshot of its sample run:

sort string in descending order c

Other Programs on Sorting String

C Online Test


« Previous Program Next Program »



© Copyright 2021. All Rights Reserved.

CodesCracker