i'm trying to find the different characters of two strings using swift. for example x="A B C" y = "A b C"
it should tell me that B is different than b
UPDATE for Swift 4.0 or greater
Because of the change of String to also be a collection, this answer can be shortened to
let difference = zip(x, y).filter{ $0 != $1 }
For Swift version 3.*
let difference = zip(x.characters, y.characters).filter{$0 != $1}
You should probably update the question to specify if you are looking for characters that do not exist in the other string or if you actually want to know if the strings are different and starting at which index.
To get a list of unique characters that only exist on one of the strings, you can do a set operation like this:
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"]
If you want to know the index where the strings begin to differ, do a loop over the characters and compare the strings index by index.
Use difference 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With