C program to sort each word from a given string in ascending order

In this article, we will learn about how to sort or arrange each word from any given string (by the user at run-time) in ascending order.

In this program, each word is sorted character-wise. For example, if the given string by the user is "this is fresherearth," Here we have a total of three words ("this," "is," and "fresherearth") present inside the string. Therefore, after sorting each word, the string will become "hist is acccdeekorrs." As you can see, all three words are sorted or arranged in ascending order.

#include<stdio.h>
#include<conio.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]>=65 && str[j]<=90)
            {
                if(str[j+1]>=65 && str[j+1]<=90)
                {
                    if(str[j]>str[j+1])
                    {
                        chTemp = str[j];
                        str[j] = str[j+1];
                        str[j+1] = chTemp;
                    }
                }
            }
            if(str[j]>=97 && str[j]<=122)
            {
                if(str[j+1]>=97 && str[j+1]<=122)
                {
                    if(str[j]>str[j+1])
                    {
                        chTemp = str[j];
                        str[j] = str[j+1];
                        str[j+1] = chTemp;
                    }
                }
            }
        }
    }
    printf("\nSame string with each word in ascending order:\n%s", str);
    getch();
    return 0;
}

The program was written in the Code::Blocks IDE; therefore, after a successful build and run, here is the sample run:

sort each word in ascending order c

Supply any string, say "how are you," and press the ENTER key to see the same string with its words sorted in ascending order as shown in the second snapshot of the sample run given here:

c sort each word in ascending order

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

C Quiz


« Previous Program Next Program »