简体   繁体   English

在Swift 2.2中按第二个字母对数组排序

[英]Sort array by second letter in swift 2.2

I want to sort the array by second letter of word. 我想按单词的第二个字母对数组排序。 Some one has an idea? 有人有主意吗? i will type a value and key, should return sorted list like this: array ["hello", "bye", "how", etc"] Sorted: hello, how, etc, bye 我将键入一个值和键,应返回如下排序列表:array [“ hello”,“ bye”,“ how”等“] Sorted:您好,如何等,bye

static func sort(keyValue: [(key:String, value:String)]) -> [(key:String, value:String)] {

    let returnValue = keyValue( {$0 < $1}

    return returnValue
}

You can use substringFromIndex with the standard sort or sortInPlace functions: 您可以将substringFromIndex与标准sortsortInPlace函数一起使用:

let strings = ["hello", "bye", "how", "etc"]
let sortedStrings = strings.sort { $0.substringFromIndex($0.startIndex.advancedBy(1)) < $1.substringFromIndex($1.startIndex.advancedBy(1)) }

As an alternative to using subStringFromIndex —an alternative suitable specifically for the case of sorting by the second character (and in case of equality; following characters lexicographically) of each string—you can use the dropFirst() method of the CharacterView of each string: 作为使用subStringFromIndex的替代方法(一种特别适合于按每个字符串的第二个字符(在相等的情况下;按字典顺序跟随的字符)进行排序的情况下的替代方法),可以使用每个字符串的CharacterViewdropFirst()方法:

let strings = ["hello", "bye", "how", "etc"]
let sortedStrings = strings
    .sort { String($0.characters.dropFirst()) < String($1.characters.dropFirst()) }

print(sortedStrings) // ["hello", "how", "etc", "bye"]

This is equivalent to the solution using substringFromIndex and advancedBy , with the upside that this will not yield a runtime exception in case the strings array contain an empty string ( "" ) (although this can be remedied for the advancedBy solution by using .advancedBy(1, limit: $0.endIndex) and .advancedBy(1, limit: $1.endIndex) for the sorting keys, respectively). 这等同于使用溶液substringFromIndexadvancedBy ,具有上侧,这将不会产生运行时异常的情况下,所述strings数组包含一个空字符串( "" )(虽然这是可以纠正的advancedBy通过使用溶液.advancedBy(1, limit: $0.endIndex)分别为排序键的.advancedBy(1, limit: $0.endIndex).advancedBy(1, limit: $0.endIndex) .advancedBy(1, limit: $1.endIndex) )。


Note also that lexicographical comparison will sort uppercase letters prior to any lowercase letter, such that ["hello", "bYe", "hOw", "etc"] will sort into ["hOw", "bYe", "hello", "etc"] . 另请注意,词典比较将在所有小写字母之前对大写字母进行排序,例如["hello", "bYe", "hOw", "etc"]将被排序为["hOw", "bYe", "hello", "etc"] If you want case-insensitive sorting, you can apply the .lowercaseString property to the sorting keys: 如果.lowercaseString区分大小写的排序,可以将.lowercaseString属性应用于排序键:

let strings = ["hello", "bYe", "hOw", "etc"]
let sortedStrings = strings
    .sort { String($0.lowercaseString.characters.dropFirst()) <
        String($1.lowercaseString.characters.dropFirst()) }

print(sortedStrings) // ["hello", "hOw", "etc", "bYe"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM