我正在尝试使用swift查找两个字符串的不同字符。 例如 x =“A B C” y =“A b C”
它应该告诉我B不同于b
答案 0 :(得分:6)
Swift 4.0或更高版本的更新
由于String的更改也是一个集合,因此可以将此答案缩短为
let difference = zip(x, y).filter{ $0 != $1 }
适用于Swift版本3。*
let difference = zip(x.characters, y.characters).filter{$0 != $1}
答案 1 :(得分:1)
您应该更新问题,以指定您是否正在查找其他字符串中不存在的字符,或者您是否真的想知道字符串是否不同并从哪个索引开始。
要获取仅存在于其中一个字符串上的唯一字符列表,您可以执行如下设置操作:
let x = "A B C"
let y = "A b C"
let setX = Set(x.characters)
let setY = Set(y.characters)
let diff = setX.union(setY).subtract(setX.intersect(setY)) // ["b", "B"]
如果你想知道字符串开始不同的索引,请对字符进行循环,并按索引比较字符串索引。
答案 2 :(得分:0)
简单的例子:
let str1 = "ABC"
let str2 = "AbC"
//convert strings to array
let str1Arr = Array(str1.characters)
let str2Arr = Array(str2.characters)
for var i = 0; i < str1Arr.count; i++ {
if str1Arr[i] == str2Arr[i] {
print("\(str1Arr[i]) is same as \(str2Arr[i]))")
} else {
print("\(str1Arr[i]) is Different then \(str2Arr[i])") //"B is Different then b\n"
}
}
用操场测试。
答案 3 :(得分:0)
使用差异API
/// Returns the difference needed to produce this collection's ordered
/// elements from the given collection.
///
/// This function does not infer element moves. If you need to infer moves,
/// call the `inferringMoves()` method on the resulting difference.
///
/// - Parameters:
/// - other: The base state.
///
/// - Returns: The difference needed to produce this collection's ordered
/// elements from the given collection.
///
/// - Complexity: Worst case performance is O(*n* * *m*), where *n* is the
/// count of this collection and *m* is `other.count`. You can expect
/// faster execution when the collections share many common elements, or
/// if `Element` conforms to `Hashable`.
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
public func difference<C>(from other: C) -> CollectionDifference<Character> where C : BidirectionalCollection, Self.Element == C.Element