Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

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

...