Write a C program that will read a word and rewrite it in alphabetical order
C program to sort a string ,Sort a string in Alphabetical order in c language
Sorting a string alphabetically is a common programming task in C and C++. In this tutorial, we will write a C program to arrange the characters of a string in alphabetical order. Additionally, we will also see how to perform the same task in C++ using the built-in sort function.
Sorting a string is useful in applications like dictionary sorting, word manipulation, and text processing.
The following C program reads a string from the user and sorts its characters in ascending order (A-Z or a-z).
#include <stdio.h>
#include <string.h>
void main() {
char str[100], temp;
int i, j;
printf("Enter a string: ");
scanf("%[^
]", str);
int length = strlen(str);
// Sorting characters using Bubble Sort
for(i = 0; i < length - 1; i++) {
for(j = i + 1; j < length; j++) {
if(str[i] > str[j]) {
// Swap characters
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
printf("Sorted string: %s\n", str);
}
Enter a string: HELLO
Sorted string: EHLLO
The same task can be performed in C++ using the sort() function from the <algorithm>
library.
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
// Sorting using the built-in sort() function
sort(str.begin(), str.end());
cout << "Sorted string: " << str << endl;
return 0;
}
sort()
function, which is more efficient than manually implementing sorting.Enter a string: HELLO
Sorted string: EHLLO
Feature | C Approach | C++ Approach |
---|---|---|
Sorting Method | Bubble Sort (Manual Sorting) |
Built-in sort() function |
Code Complexity | Higher (Nested Loops) | Lower (One Line Sort) |
Efficiency | O(n²) (Slow for large strings) | O(n log n) (Faster Sorting) |
Sorting strings alphabetically is useful in: ✔ Lexicographic sorting – Used in dictionaries and word processing
✔ Anagram detection – Checking if two words have the same letters
✔ Text analysis – Preprocessing text data for machine learning
✔ Generating permutations – Useful in cryptography and data processing
In this tutorial, we learned how to sort a string alphabetically in C and C++. The C program uses Bubble Sort, while the C++ program takes advantage of the sort() function from the algorithm library.
If you’re working with large datasets, C++ is recommended due to its optimized sorting functions. Mastering string sorting techniques is crucial for programming interviews and competitive coding! 🚀
🔹 C Program to Reverse a String
🔹 C++ Program to Check Anagram Strings
🔹 Sorting Algorithms in C++
Let me know if you need further improvements! 😊 🚀