如何在不丢失顺序的情况下删除 Swift 中字符串的重复行?
How to remove duplicates of lines of a String in Swift without lost their order?
我想用 Swift 3 删除字符串中的重复行。我必须这样做,但不幸的是,在过程结束时,这些行丢失了顺序。这是我的代码:
// string with 7 lines and 2 duplicates (MacBook and Mac mini)
var str = "MacBook\nMacBook Pro\nMacPro\nMacBook\niMac\nMac mini\nMac mini"
var components = str.components(separatedBy: .newlines)
print(components)
// remove duplicates: first by converting to a Set
// and then back to Array (found in iSwift.org)
components = Array(Set(components))
print(components)
let newStr = components.joined(separator: "\n")
print(newStr)
编辑:删除重复项时,我更喜欢保留第一个而不是最后一个。
调整@LeoDabus 的评论…
let str = "MacBook\nMacBook Pro\nMacPro\nMacBook\niMac\nMac mini\nMac mini"
let components = str.components(separatedBy: .newlines)
let depDuped = components.reduce([]) {
[=10=].0.contains([=10=].1) ? [=10=].0 : [=10=].0 + [[=10=].1]
}.joined(separator: "\n")
如果重复项可以出现在字符串的其他地方(因此 "A\nB\nA"
将保持不变),则
let depDuped = components.reduce([]) {
[=11=].0.last == [=11=].1 ? [=11=].0 : [=11=].0 + [[=11=].1]
}.joined(separator: "\n")
您可以使用 NSOrderedSet。
var str = "MacBook\nMacBook Pro\nMacPro\nMacBook\niMac\nMac mini\nMac mini"
var components = str.components(separatedBy: .newlines)
print(components)
let orderedSet = NSOrderedSet(array: components)
components = orderedSet.array as! [String]
print(components)
let newStr = components.joined(separator: "\n")
print(newStr)
我想用 Swift 3 删除字符串中的重复行。我必须这样做,但不幸的是,在过程结束时,这些行丢失了顺序。这是我的代码:
// string with 7 lines and 2 duplicates (MacBook and Mac mini)
var str = "MacBook\nMacBook Pro\nMacPro\nMacBook\niMac\nMac mini\nMac mini"
var components = str.components(separatedBy: .newlines)
print(components)
// remove duplicates: first by converting to a Set
// and then back to Array (found in iSwift.org)
components = Array(Set(components))
print(components)
let newStr = components.joined(separator: "\n")
print(newStr)
编辑:删除重复项时,我更喜欢保留第一个而不是最后一个。
调整@LeoDabus 的评论…
let str = "MacBook\nMacBook Pro\nMacPro\nMacBook\niMac\nMac mini\nMac mini"
let components = str.components(separatedBy: .newlines)
let depDuped = components.reduce([]) {
[=10=].0.contains([=10=].1) ? [=10=].0 : [=10=].0 + [[=10=].1]
}.joined(separator: "\n")
如果重复项可以出现在字符串的其他地方(因此 "A\nB\nA"
将保持不变),则
let depDuped = components.reduce([]) {
[=11=].0.last == [=11=].1 ? [=11=].0 : [=11=].0 + [[=11=].1]
}.joined(separator: "\n")
您可以使用 NSOrderedSet。
var str = "MacBook\nMacBook Pro\nMacPro\nMacBook\niMac\nMac mini\nMac mini"
var components = str.components(separatedBy: .newlines)
print(components)
let orderedSet = NSOrderedSet(array: components)
components = orderedSet.array as! [String]
print(components)
let newStr = components.joined(separator: "\n")
print(newStr)