如何按字母顺序对字符串的字符进行排序? [英] How to sort a string's characters alphabetically?

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

问题描述

对于数组,有一个漂亮的sort方法可以重新排列元素的序列.我想为String达到相同的结果.

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

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

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

是否有本机启用此功能,还是应该包含Enumerable中的mixins?

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

推荐答案

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

The chars method returns an enumeration of the string's characters.

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

不区分大小写进行排序:

To sort case insensitively:

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

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

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