codescracker


c

C Program to sort each Word from given String in Ascending Order



« C Tutorial C Examples »

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

In this program, Each word is sorted character wise, for example if the given string by user will be this is codescracker. Here we have total of three words present inside the string, therefore we have to sort all the three words inside the string that is this, is and codescracker are the three words to be sorted in ascending order. Here after sorting the string, it will become hist is acccdeekorrs. As you can see that, all the three words are sorted or arranged in ascending order. Now let's take a look at the program:

// Write a program in C to sort each word from given
// string in ascending order
// for example, if string is "how are you"
// then after sorting each word in ascending order,
// the string has to become "how aer ouy"
// -----------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]>=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 under Code::Blocks IDE, therefore after successful build and run, here is the sample run. This is the first snapshot:

sort each word in ascending order c

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

c sort each word in ascending order

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


« C Tutorial C Examples »






Tools
Calculator

Quick Links
Signup - Login - Give Online Test