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

11
我试图使用Swift找出两个字符串之间的不同字符。 例如: x="A B C" y = "A b C"
它应该告诉我B与b不同。
4个回答

17

Swift 4.0或更高版本的更新

由于String也成为了一个集合类型,因此可以将本答案简化为:

let difference = zip(x, y).filter{ $0 != $1 }

对于 Swift 版本 3.*

let difference = zip(x.characters, y.characters).filter{$0 != $1}

输入图像描述


4
只有当两个字符串长度相等时,这才会起作用... - jayant rawat

3

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

要获取仅存在于一个字符串中的唯一字符列表,您可以执行像这样的集合操作:

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

如果您想知道字符串开始不同的索引,请循环遍历字符并逐个比较字符串的索引。


3

使用不同的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

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

已在游乐场中测试。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接