我试图使用Swift找出两个字符串之间的不同字符。
例如:
x="A B C"
y = "A b C"
它应该告诉我B与b不同。
它应该告诉我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"]
如果您想知道字符串开始不同的索引,请循环遍历字符并逐个比较字符串的索引。
使用不同的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
这里有一个简单的例子:
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"
}
}
已在游乐场中测试。