排序C ++字符串的字符

时间:2012-02-02 05:20:21

标签: c++ string sorting

如果我有一个字符串,那么有一个内置函数来对字符进行排序,还是我必须自己编写?

例如:

string word = "dabc";

我想改变它,以便:

string sortedWord = "abcd";

也许使用char是更好的选择?我怎么用C ++做这个?

4 个答案:

答案 0 :(得分:126)

标准库中有a sorting algorithm,标题为<algorithm>。它排序到位,所以如果你执行以下操作,你的原始单词将被排序。

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

如果您不想丢失原件,请先复印一份。

std::string sortedWord = word;
std::sort(sortedWord.begin(), sortedWord.end());

答案 1 :(得分:13)

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

请参阅here

答案 2 :(得分:1)

您必须在sort头文件中包含algorithm函数,该文件在c ++中为standard template library

用法: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;
}

<强>输出:

  

abcd

答案 3 :(得分:0)

您可以使用sort()功能。 sort()存在于algorithm头文件

        #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;
        }

输出

  

achklors