In this tutorial you will learn about the C Program to Sort a String and its application with practical example.
C Program to Sort a String
In this tutorial, we will learn to create a C program that will Sort a String in C programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- For loop in c programming.
- String functions of c programming.
- Conditional Statements in the C programming
Sort a String
As we all know the String is a collection of character data types. In strings, only one variable is declared which can store multiple values. First, we will give the input string to the program. Then will Sort a String by finding its length and sending it to a for loop with conditional statements in nested for loop.
With the help of this program, we can Sort a String.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declare the variables for the program. 2. Give the input string from the user. 3. Passing that string to nested for loop. 4. Sorting with the conditional statements. 5. Print the string. 6. End the program. |
Program to Sort a String:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
/* C Program to Sort a String */ #include <stdio.h> //inporting the string.h file for supportof the string functions #include <string.h> int main () { //declaring the variables for the program char string[] = "w3addalearning"; char temp; int i, j; //Getting the length of the string int no = strlen(string); //Printing before sorting the string printf("String before sorting - %s \n", string); for (i = 0; i < no-1; i++) { for (j = i+1; j < no; j++) { if (string[i] > string[j]) { temp = string[i]; string[i] = string[j]; string[j] = temp; } } } //Printing After sorting the string printf("String after sorting - %s \n", string); return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- string[] = it will hold the string value.
- temp = it will hold the string value.
- i = it will hold the string value.
- j = it will hold the string value.
Finding the length of the string.
Printing before sorting.
Printing the output.