Swift 获取两个字符串中的不同字符

Swift get the different characters in two strings

我正在尝试使用 swift 查找两个字符串的不同字符。 例如 x="A B C" y = "A b C"

它应该告诉我 B 不同于 b

您可能应该更新问题以指定您是否正在寻找另一个字符串中不存在的字符,或者您是否真的想知道字符串是否不同以及从哪个索引开始。

要获取仅存在于其中一个字符串中的唯一字符的列表,您可以执行如下设置操作:

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"]

如果您想知道字符串开始不同的索引,请对字符进行循环并按索引比较字符串。

给你的简单例子:

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"
    }
}

已在 playground 上测试。

更新 Swift 4.0 或更高版本

由于String也变成了一个集合,这个答案可以缩短为

let difference = zip(x, y).filter{ [=10=] !=  }

对于 Swift 版本 3.*

let difference = zip(x.characters, y.characters).filter{[=11=] != }

使用差异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