我尝试按如下方式对数组进行排序:
let students: Set = ["23412334","&234@fwv","Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let sortedStudents = students.sorted()
print(sortedStudents)
输出:
["&234@fwv", "23412334", "Abena", "Akosua", "Kofi", "Kweku", "Peter"]
但我需要像
["Abena", "Akosua", "Kofi", "Kweku", "Peter", "23412334","&234@fwv"]
答案 0 :(得分:4)
let words = ["23412334","&234@fwv","Kofi", "Abena", "Peter", "Kweku", "Akosua"]
func sortedNumbersLast(words: [String]) -> [String] {
var startsWithDigit = [String]()
var startsWithCharacter = [String]()
var startsWithSymbol = [String]()
for word in words {
if let first = word.characters.first {
if first >= "0" && first <= "9" {
startsWithDigit.append(word)
}
else {
if(!(first >= "a" && first <= "z") && !(first >= "A" && first <= "Z") ){
startsWithSymbol.append(word)
}else{
startsWithCharacter.append(word)
}
}
}
}
return startsWithCharacter.sorted(by: <) + startsWithDigit.sorted(by: <) + startsWithSymbol.sorted()
}
print(sortedNumbersLast(words: words))
["Abena", "Akosua", "Kofi", "Kweku", "Peter", "23412334", "&234@fwv"]
答案 1 :(得分:3)
&#34;正确&#34;这样做的方法是定义自己的排序比较器并使用extension String
{
enum Priority
{
case normal
case low
case lowest
static let lowPriority: Set<Character> = Set(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"])
static let lowestPriority: Set<Character> = Set(["&"])
static func < (a: Priority, b: Priority) -> Bool
{
switch (a, b)
{
case (.normal, .low), (.normal, .lowest), (.low, .lowest):
return true
default:
return false
}
}
}
var priority: Priority
{
let first = self.characters.first! // fatal error for empty strings
if Priority.lowestPriority.contains(first)
{
return .lowest
}
else if Priority.lowPriority.contains(first)
{
return .low
}
return .normal
}
}
let students: Set = ["23412334","&234@fwv","Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let sortedStudents = students.sorted {
(a, b) -> Bool in
if a.priority < b.priority
{
return true
}
else if b.priority < a.priority
{
return false
}
return a < b
}
print(sortedStudents)
使用比较器进行排序。在下面的示例中,我定义了一个&#34;优先级&#34;基于字符串中第一个字符的类别,然后是基于优先级的二级排序,然后是正常的字符串排序
public class DateTime implements Comparator<DateTime>, Comparable<DateTime> {
...
@Override
public int compareTo(DateTime dateTime) {
if (year > dateTime.year) {
return 1;
} else if (month > dateTime.month) {
return 1;
} ...
}
@Override
public int compare(DateTime dateTime1, DateTime dateTime2) {
return dateTime1.compareTo(dateTime2)
}
}
可能还有错误,但它适用于您的测试用例。
答案 2 :(得分:0)
请按照以下步骤操作
首先按排序对数组进行排序。
删除以特殊字符开头的字符串,并将其保存在另一个数组中。