Search code examples
swiftuppercaselowercase

German character ß uppercased in SS


I figured out, that "ß" is converted to "SS" when using uppercased(). But I want compare if two strings are equal without being case sensitive. So when comparing "gruß" with "GRUß" it should be the same as well as when comparing "gru" with "Gru". There is no uppercase "ß" in german language! Because I don't know which other characters aren't available in the corresponding languages, I could not filter all the caracters, which have no 1:1 uppercased opponent. What can I do?


Solution

  • Use caseInsensitiveCompare() instead of converting the strings to upper or lowercase:

    let s1 = "gruß"
    let s2 = "GRUß"
    
    let eq = s1.caseInsensitiveCompare(s2) == .orderedSame
    print(eq) // true
    

    This compares the strings in a case-insensitive way according to the Unicode standard.

    There is also localizedCaseInsensitiveCompare() which does a comparison according to the current locale, and

    s1.compare(s2, options: .caseInsensitive, locale: ...)
    

    for a case-insensitive comparison according to an arbitrary given locale.