排序C ++字符串的字符 [英] Sorting Characters Of A C++ String

查看:166
本文介绍了排序C ++字符串的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If i have a string is there a built in function to sort the characters or would I have to write my own?

例如:

string word = "dabc";

我想更改它,以便:

string sortedWord = "abcd";

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

Maybe using char is a better option? How would I do this in C++?

推荐答案

< algorithm> 中的标题库中的w / cpp / algorithm / sort>排序算法。它排在现场,所以如果你做以下,你的原始单词将排序。

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

这篇关于排序C ++字符串的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆