Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift get the different characters in two strings

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

like image 264
Sara Avatar asked Oct 16 '15 04:10

Sara


3 Answers

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}

enter image description here

like image 102
Price Ringo Avatar answered Nov 09 '22 13:11

Price Ringo


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.

like image 3
Eneko Alonso Avatar answered Nov 09 '22 13:11

Eneko Alonso


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
like image 1
amleszk Avatar answered Nov 09 '22 15:11

amleszk