0

I have two string and i need to find out the number of matching character at the same position into the strings. Ex- 1010 and 1100, two character have matched at position 1 and 4. Is there any way to find out it easily in swift?

I have placed each character in an array of the first string and tried to mach like--

for chr in string2 {
    if chr == array[i] {
        count += 1
    }
}

That was my approach but if there any easiest solution.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
  • I have placed each character in an array of the first string and tried to mach like-- for chr in string2 { if chr == array[i] { count += 1}} – Taohidur Imran Apr 21 '19 at 09:15
  • Since `String` is a `Collection` (`BidirectionalCollection` more specifically), it should be considered as a duplicate. – Ahmad F Apr 21 '19 at 09:42
  • @AhmadF I don't think this is a duplicate. The matching should be made at a given index. This is not the same as the intersection of two sets... – ielyamani Apr 21 '19 at 11:14

1 Answers1

2

You can use zip to find out the number of matching characters in the same position.

let x = "1010"
let y = "1100"

let intersection = zip(x, y).filter{ $0 == $1 }
let numberOfMatches = intersection.count
Mihai Panţiru
  • 513
  • 3
  • 16