How to case-insensitively check if a character exists in a string with Swift

1 Answer

0 votes
import Foundation

// Case-insensitive check without a loop
func charExistsIgnoreCase(_ s: String, _ target: Character) -> Bool {
    // Convert both to lowercase and use contains()
    return s.lowercased().contains(String(target).lowercased())
}

// Define the string we want to search in
let s = "SwiftLanguage"

// Perform the case-insensitive check
let exists = charExistsIgnoreCase(s, "s")

// Print the raw boolean result
print(exists)

// Conditional check
if exists {
    print("exists")
} else {
    print("not exists")
}



/*
run:

true
exists

*/

 



answered Jun 26 by avibootz

Related questions

...