我想用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)
编辑:当删除重复时,我更喜欢保留第一个而不是最后一个。
3条答案
按热度按时间oewdyzsn1#
Tweaking @LeoDabus' comment.
如果重复可以出现在字符串中的其他地方(因此
"A\nB\nA"
将保持不变),则6g8kf2rb2#
您可以使用NSOrderedSet。
zf2sa74q3#
Swift 5更新来自@ashley-mills