How to check if two equal-length strings are at least 50% equal in Swift

1 Answer

0 votes
import Foundation

func atLeastHalfEqual(_ s1: String, _ s2: String) -> Bool {
    // Check equal length and non‑empty
    guard !s1.isEmpty, s1.count == s2.count else {
        return false
    }

    var matches = 0
    let len = s1.count

    // Compare character‑by‑character (Pascal semantics)
    // Swift Strings are Unicode-aware, so we zip characters
    for (c1, c2) in zip(s1, s2) {
        if c1 == c2 {
            matches += 1
        }
    }

    // matches / len ≥ 0.5  →  2 * matches ≥ len
    return matches * 2 >= len
}

let str1 = "abcde"
let str2 = "axcfz"

print(atLeastHalfEqual(str1, str2))  

print(
    atLeastHalfEqual(
        "javascript c# c++ c python",
        "javascript c# r c rust SQL"
    )
)



/*
run:

false
true

*/

 



answered Dec 21, 2025 by avibootz

Related questions

...