codescracker


c

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



« C Tutorial C Examples »

Sort Strings in C

To sort each word from given string (by user at run-time) in alphabetical order in C programming, you have to ask from the user to enter some set of words or names as string (here user is allowed to enter 5 words as string). Now start comparing one words with other and sort all the words in alphabetical order to display all the words as string arranged in alphabetical order as shown here in the following program.

C Programming Code to Sort Strings in Alphabetical Order

Following C program will ask from the user to enter five names as string to sort them in alphabetical order, then display the sorted strings in alphabetical order on the screen:

// Write a program in C, to sort each words
// in given string in alphabetical order.
// For example if user provides following
// 5 words (names) as strings:
// gaurav
// alok
// shivam
// hritik
// deepak
// Then the output will be
// alok
// deepak
// gaurav
// hritik
// shivam
// ---------codescracker.com--------

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
	char str[5][20], t[20];
	int i, j;
	printf("Enter any string (5 names):\n");
	for(i=0; i<5; i++)
	{
		scanf("%s", str[i]);
	}
	for(i=1; i<5; i++)
	{
		for(j=1; j<5; j++)
		{
			if(strcmp(str[j-1], str[j])>0)
			{
				strcpy(t, str[j-1]);
				strcpy(str[j-1], str[j]);
				strcpy(str[j], t);
			}
		}
	}
	printf("\nStrings (Names) in alphabetical order:\n");
	for(i=0; i<5; i++)
	{
		printf("%s\n", str[i]);
	}
	getch();
	return 0;
}

The program was written under Code::Blocks IDE, therefore after successful build and run, here is the sample run of the above program. This is the first snapshot:

c program sort string

Now supply any five names as string and press ENTER key to see the string with its each word sorted in alphabetical order as shown here in the second snapshot.

You have to provide all the 5 names as string one by one. That is, supply first name say Gaurav and press ENTER key, then supply second name say Shivam and press ENTER key and so on.

c sort words in alphabetical order

As the function used here to get the string input from user is scanf(), therefore you can also provide all the 5 names as string in one line say Gaurav Hritik Deepak Alok Shivam. Here is the final snapshot of the sample run in this case:

sort each word in string alphabetical order

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


« C Tutorial C Examples »






Tools
Calculator

Quick Links
Signup - Login - Give Online Test