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

String Swift获取两个字符串中的不同字符,string,swift,character,String,Swift,Character,我正在尝试使用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 =

我正在尝试使用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"
    }
}
让str1=“ABC”
让str2=“AbC”
//将字符串转换为数组
设str1Arr=数组(str1.characters)
设str2Arr=数组(str2.characters)
对于var i=0;i

使用游乐场进行测试。

更新Swift 4.0或更高版本

因为字符串也被更改为集合,所以这个答案可以缩短为

let difference = zip(x, y).filter{ $0 != $1 }
适用于Swift第3版。*

let difference = zip(x.characters, y.characters).filter{$0 != $1}
使用差异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
///返回生成此集合的排序所需的差异
///来自给定集合的元素。
///
///此函数不推断元素移动。如果你需要推断动作,
///对结果差异调用'inferringMoves()`方法。
///
///-参数:
///-其他:基态。
///
///-返回:生成此集合的订单所需的差异
///来自给定集合的元素。
///
///-复杂性:最坏情况下的性能是O(*n***m*),其中*n*是
///此集合的计数,*m*是'other.count'。你可以期待
///当集合共享许多公共元素或
///如果'Element'符合'Hashable'。
@可用(OSX 10.15、iOS 13、tvOS 13、watchOS 6、*)
public func difference(来自其他:C)->CollectionDifference,其中C:BidirectionalCollection,Self.Element==C.Element

只有当两个字符串长度相等时,此操作才有效。。。