【问题标题】:Sorting Characters Of A C++ String对 C++ 字符串的字符进行排序
【发布时间】:2012-02-24 19:45:39
【问题描述】:

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

例如:

string word = "dabc";

我想改变它:

string sortedWord = "abcd";

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

【问题讨论】:

  • std::sort 呢?
  • 请注意,任何类型的基于 char 值的简单排序都会因 UTF-8 而中断 - 根据您的字符串,您可能需要考虑语言环境。

标签: c++ string sorting


【解决方案1】:

标准库中有a sorting algorithm,在标头<algorithm>中。它会就地排序,因此如果您执行以下操作,您的原始单词将被排序。

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

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

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

【讨论】:

  • 如果我们希望字符串按升序排序怎么办?
  • @madhuspot std::sort 默认按字母升序排序。假设这是一个小错字并且您想要de增加顺序,请使用std::sort 的版本,该版本将Compare 作为其第三个参数并提供std::greater 而不是默认的std::lessstd::string 默认使用 char 类型,例如std::sort(sortedWord.begin(), sortedWord.end(), std::greater<char>()); — 这将在原始问题中给出“dcba”而不是“abcd”的结果。
  • @madhuspot 或使用 std::reverse
【解决方案2】:
std::sort(str.begin(), str.end());

here

【讨论】:

  • 这是最好的方法...如果字符串使用单字节编码。否则,您会将字符分解为其组成字节。
【解决方案3】:

您必须包含 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

【讨论】:

    【解决方案4】:

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

    输出:

    阿克洛尔

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      • 2012-08-31
      • 2013-11-21
      • 1970-01-01
      • 2021-09-17
      • 2012-11-14
      相关资源
      最近更新 更多