排序字母数字数组,连续数字应该最后驻留 [英] Sort alphanumeric array, consecutive numbers should reside at last

查看:91
本文介绍了排序字母数字数组,连续数字应该最后驻留的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对字母数字进行排序,但数字应该在结尾而不是开头。例如

I want to sort an alphanumeric, but numbers should come at end instead of beginning. for instance

let array = ["1", "a", "b", "z", "3", "!"]
let sortedArray = array.sort { (firstObject, secondObject) -> Bool in
    firstObject < secondObject
}

输出:


[!,1,3,a,b,z]

["!", "1", "3", "a", "b", "z"]

必需输出:


[a ,b,z,1,3,!]

["a", "b", "z", "1", "3", "!"]

提前致谢。

推荐答案

这是适合您案例的解决方案:

Here's a solution that works for your case :

预期结果是:


  • 信件优先;

  • 然后是数字;

  • 然后是其他人;

这是一种方法。

// Works with both arrays
var array = ["1", "b", "a", "z", "3", "!"]
//var array = ["1", "b", "A", "Z", "3", "!"]

func isLetter(char: String) -> Bool {
    return ("a"..."z").contains(char) || ("A"..."Z").contains(char)
}

func isNumber(char: String) -> Bool {
    return Int(char) != nil
}

let letters = array.filter(isLetter).sort{$0.lowercaseString < $1.lowercaseString}
let numbers = array.filter(isNumber).sort{Int($0) < Int($1)}
let others = Array(Set(array).subtract(letters).subtract(numbers)).sort{$0 < $1}

let sortedArray = letters + numbers + others

第一个数组将

["a", "b", "z", "1", "3", "!"]

第二个是

["A", "b", "Z", "1", "3", "!"]

它可以满足您的需求。包括单元测试并将其包装在方法中,你很高兴。 Buuuut,它根本不是干净。

It does what you want. Include unit tests and wrap that inside a method and you're good to go. Buuuut, it's not "clean" at all.

这篇关于排序字母数字数组,连续数字应该最后驻留的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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