C++ Program to sort string in alphabetical order


In this program, You will learn how to sort string in alphabetical order in C++.


List of unsorted string: abc, kbc, xiith, john

List of sorted string in alphabetical order: abc, bck, hiitx, jhno


Example: How to sort string in alphabetical order in C++

Run it Now
#include<iostream>
#include<cstring>
using namespace std;

int main() {

    int i, j, temp, size;
    char str[100];

    cout << "Enter a String :";
    cin.getline(str, 100);

    size = strlen(str);

    for (i = 0; i < size; i++) {
        for (j = i + 1; j < size; j++) {
            if (str[i] > str[j]) {
                temp = str[i];
                str[i] = str[j];
                str[j] = temp;
            }
        }
    }
    cout << "\nSorted in Alphabetical Order :" << str;

    return 0;
}

Output:

Enter a String :bcb
Sorted in Alphabetical Order :bbc