排序字符的C + +字符串

问题描述:

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

例如:

string word = "dabc"; 

我想改变它,以便:

string sortedWord = "abcd"; 

也许使用字符是一个更好的选择?我将如何在C++中执行此操作?

+7

什么'性病:: sort'? – dreamlax 2012-02-02 05:21:38

+0

请注意,任何种类的基于幼稚字符值的排序都会以UTF-8为基础 - 取决于您想要考虑语言环境的字符串。 – 2017-11-17 10:44:06

有一个在标准库a sorting algorithm,在报头中<algorithm>。它排序,所以如果你做了以下,你的原始单词将被分类。

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

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

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

谢谢,我现在觉得很蠢,太多的PHP ... – gprime 2012-02-02 06:28:37

+0

如果我们想让字符串按递增顺序排序呢? – madhuspot 2017-06-16 14:09:33

+2

默认情况下,@madhuspot'std :: sort'按字母顺序递增排序。假设这是一个小错字,并且你想要压缩命令,可以使用'std :: sort'版本,它将'Compare'作为它的第三个参数,并提供'std :: greater'而不是默认的'std :: less'。 'std :: string'默认使用'char'类型,例如'std :: sort(sortedWord.begin(),sortedWord)。end(),std :: greater ());' - 这会在原始问题中给出“dcba”的结果而不是“abcd”。 – Tommy 2017-07-10 00:19:36

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

here参见

+10

这是最好的方法......如果字符串使用单字节编码。否则,您会将字符分解为其组件字节。 – 2012-02-02 05:34:27

+0

@BenVoigt:优点! – dreamlax 2012-02-02 05:36:38

你必须包括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; 
} 

OUTPUT:

abcd

可以使用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

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

如何将在内部执行,请解释逻辑

+0

我不理解你的评论“如何执行内部请解释逻辑”。 – 2017-11-17 10:39:34