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++.

#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 << "Sorted in Alphabetical order:" << str;

    return 0;
}

Output:

Enter a string:xiith
Sorted in Alphabetical order:hiitx