ruby 如何按字母顺序对字符串的字符进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9464065/
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-09-06 04:49:30  来源:igfitidea点击:

How to sort a string's characters alphabetically?

rubystringsorting

提问by steveyang

For Array, there is a pretty sortmethod to rearrange the sequence of elements. I want to achieve the same results for a String.

对于 Array,有一个很好的sort方法来重新排列元素的序列。我想为字符串实现相同的结果。

For example, I have a string str = "String", I want to sort it alphabetically with one simple method to "ginrSt".

例如,我有一个字符串str = "String",我想用一种简单的方法按字母顺序对它进行排序"ginrSt"

Is there a native way to enable this or should I include mixins from Enumerable?

是否有一种本地方式可以启用此功能,或者我应该包含来自 的mixinEnumerable吗?

回答by molf

The charsmethodreturns an enumeration of the string's characters.

chars方法返回字符串字符的枚举。

str.chars.sort.join
#=> "Sginrt"

To sort case insensitively:

不区分大小写排序:

str.chars.sort(&:casecmp).join
#=> "ginrSt"

回答by fl00r

Also (just for fun)

还有(只是为了好玩)

str = "String"
str.chars.sort_by(&:downcase).join
#=> "ginrSt"

回答by user2386335

str.unpack("c*").sort.pack("c*")

回答by leandrotk

You can transform the string into an array to sort:

您可以将字符串转换为数组进行排序:

'string'.split('').sort.join