Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Characters Of A C++ String

If i have a string is there a built in function to sort the characters or would I have to write my own?

for example:

string word = "dabc";

I would want to change it so that:

string sortedWord = "abcd";

Maybe using char is a better option? How would I do this in C++?

like image 734
gprime Avatar asked Feb 02 '12 05:02

gprime


People also ask

How do I sort characters in a string?

The main logic is to toCharArray() method of the String class over the input string to create a character array for the input string. Now use Arrays. sort(char c[]) method to sort character array. Use the String class constructor to create a sorted string from a char array.

How do you sort a character in C#?

Firstly, set a string array. string[] values = { "tim", "amit", "tom", "jack", "saurav"}; Use the Sort() method to sort.

Can I sort a string C++?

Sort characters of a string in C++ The standard and efficient solution to inplace sort characters of a string is using the std::sort algorithm from header <algorithm> . It is usually implemented using the Introsort algorithm, which is a hybrid of quicksort, heapsort, and insertion sort.

How do you sort a char array in C++?

char charArray[] = {'A','Z', 'K', 'L' }; size_t arraySize = sizeof(charArray)/sizeof(*charArray); std::sort(charArray, charArray+arraySize); //print charArray : it will print all chars in ascending order. By the way, you should avoid using c-style arrays, and should prefer using std::array or std::vector .


3 Answers

There is a sorting algorithm in the standard library, in the header <algorithm>. It sorts inplace, so if you do the following, your original word will become sorted.

std::sort(word.begin(), word.end());

If you don't want to lose the original, make a copy first.

std::string sortedWord = word;
std::sort(sortedWord.begin(), sortedWord.end());
like image 199
R. Martinho Fernandes Avatar answered Oct 18 '22 18:10

R. Martinho Fernandes


std::sort(str.begin(), str.end());

See here

like image 28
dreamlax Avatar answered Oct 18 '22 19:10

dreamlax


You have to include sort function which is in algorithm header file which is a standard template library in c++.

Usage: std::sort(str.begin(), str.end());

#include <iostream>
#include <algorithm>  // this header is required for std::sort to work
int main()
{
    std::string s = "dacb";
    std::sort(s.begin(), s.end());
    std::cout << s << std::endl;

    return 0;
}

OUTPUT:

abcd

like image 3
abe312 Avatar answered Oct 18 '22 18:10

abe312