用数字按字母顺序对数组进行排序 [英] Sorting array alphabetically with number

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

问题描述

myArray = [Step 6, Step 12, Step 5, Step 14, Step 4, Step 11, Step 16, Step 9, 
Step 3, Step 13, Step 8, Step 2, Step 10, Step 7, Step 1, Step 15]

如何以这种方式在上方对这个数组进行排序?

How can I sort this array above in this way?

[Step 1, Step 2, Step 3, Step 4, ....]

我在迅速sort(&myArray,{ $0 < $1 })中使用了此功能,但它是以这种方式排序的

I used this function in swift sort(&myArray,{ $0 < $1 }) but it was sorted this way

[Step 1, Step 10, Step 11, Step 12, Step 13, Step 14, Step 15, Step 16, Step 2, 
 Step 3, Step 4, Step 5, Step 6, Step 7, Step 8, Step 9]

推荐答案

另一个变种是使用 localizedStandardCompare: .从文档中:

Another variant is to use localizedStandardCompare:. From the documentation:

无论何时文件名或其他字符串都应使用此方法 显示在类似Finder排序的列表和表格中 合适的.

This method should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate.

这将根据当前语言环境对字符串进行排序. 示例:

This will sort the strings as appropriate for the current locale. Example:

let myArray = ["Step 6", "Step 12", "Step 10"]

let ans = sorted(myArray,{ (s1, s2) in 
    return s1.localizedStandardCompare(s2) == NSComparisonResult.OrderedAscending
})

println(ans)
// [Step 6, Step 10, Step 12]

更新:上面的答案很旧,适用于Swift 1.2. Swift 3 版本是(感谢@Ahmad):

Update: The above answer is quite old and for Swift 1.2. A Swift 3 version is (thanks to @Ahmad):

let ans = myArray.sorted {
    (s1, s2) -> Bool in return s1.localizedStandardCompare(s2) == .orderedAscending
}

有关其他方法,请参见 https://stackoverflow.com/a/31209763/1187415 , 在 https://stackoverflow.com/a/39748677/1187415 上翻译为Swift 3.

For a different approach see https://stackoverflow.com/a/31209763/1187415, translated to Swift 3 at https://stackoverflow.com/a/39748677/1187415.

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

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