C + + 字符串的字符排序

如果我有一个字符串是否有一个内置的函数来排序字符或者我必须写自己的?

例如:

string word = "dabc";

我想改变它,以便:

string sortedWord = "abcd";

也许使用 char 是一个更好的选择? 如何在 C + + 中做到这一点?

202657 次浏览
std::sort(str.begin(), str.end());

See here

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());

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

You can use sort() function. sort() exists in algorithm header file

        #include<bits/stdc++.h>
using namespace std;




int main()
{
ios::sync_with_stdio(false);
string str = "sharlock";


sort(str.begin(), str.end());
cout<<str<<endl;


return 0;
}

Output:

achklors