如何在不丢失命令的情况下删除Swift中String的重复行?

时间:2017-03-16 15:17:20

标签: swift string duplicates lines

我想用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)

编辑:删除重复项时,我更喜欢保留第一个不是最后一个。

2 个答案:

答案 0 :(得分:1)

调整@LeoDabus'评论......

let str = "MacBook\nMacBook Pro\nMacPro\nMacBook\niMac\nMac mini\nMac mini"
let components = str.components(separatedBy: .newlines)

let depDuped = components.reduce([]) {
    $0.0.contains($0.1) ? $0.0 : $0.0 + [$0.1]
}.joined(separator: "\n")

如果字符串中的其他地方可能出现重复项(因此"A\nB\nA"将保持不变),那么

let depDuped = components.reduce([]) {
    $0.0.last == $0.1 ? $0.0 : $0.0 + [$0.1]
}.joined(separator: "\n")

答案 1 :(得分:1)

您可以使用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)
相关问题