对 C++ 字符串的字符进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9107516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:18:09  来源:igfitidea点击:

Sorting Characters Of A C++ String

c++stringsorting

提问by gprime

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

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

回答by R. Martinho Fernandes

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

标准库中有一个排序算法,在 header 中<algorithm>。它就地排序,因此如果您执行以下操作,您的原始单词将被排序。

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

回答by dreamlax

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

See here

这里

回答by abe312

You have to include sortfunction which is in algorithmheader file which is a standard template libraryin c++.

您必须包含头文件中的sort函数,该函数是C++ 中algorithm标准模板库

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

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

abcd

回答by rashedcs

You can use sort()function. sort() exists in algorithmheader file

您可以使用sort()函数。sort() 存在于算法头文件中

        #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

阿克洛尔