Sort Characters in a String

less than 1 minute read

The code has been modified slightly and now uploaded to the site.

Question

<— Return Home

104.cpp

#include <iostream>
#include <string>
#include "Sort104.h"
using namespace std;

int main(){
    std::string s;

    std::cout << "Enter a string s: \n";
    std::cin >> s;

    Sort104 sort(s);

    std::cout << "The sorted string is " << sort.sort(s) << "\n";
}

<— Return Home

Sort104.h

#ifndef Sort104_H
#include <string>
#define Sort104_H

class Sort104{
    public:
        Sort104(std::string& s);
        std::string sort(std::string& s);
};

#endif

<— Return Home

Sort104.cpp

#include "Sort104.h"
#include <string>

Sort104::Sort104(std::string& s){
    
}

std::string Sort104::sort(std::string& s){
    std::string store = "";
    // std::string append = "";
    for (int i = 0; i < s.length(); i++){
        for (int j = i + 1; j < s.length(); j++){
            if (s.substr(i, 1) > s.substr(j, 1)){
                store = s.substr(i, 1);
                // s.substr(i, 1).replace(s.substr(j, 1));
                s.replace(i, 1, s.substr(j, 1));
                // s.substr(j, 1).insert(store);
                s.replace(j, 1, store);
                // append += s.substr(i, 1);
                // break;
            }
            // else {
            //     append += s.substr(j, 1);
            // }
        }
    }
    return s;
}

<— Return Home