Home > database >  How to get original characters from string if compare strings
How to get original characters from string if compare strings

Time:01-17

I am trying get original characters when user taps characters with lowercase or uppercase.

For example: User writes to search bar "hello". When I compare characters with lowercase I get the result that it is true. But I am trying to get original characters from the string ("HEllo").

let string = "HELlo WORld"

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    
    if searchBar.text != nil && searchBar.text != "" {
        
        if string.lowercased().contains(searchText.lowercased()) {
                
               print("true")
               // searchText is hello
               // I want to get HELlo from string
        }
    }
}

CodePudding user response:

Rather than use the contains function, use the range(of: then apply that to your original string:

func find(_ searchText: String, in string: String) -> String {
    if let range = string.range(of: searchText, options: [.caseInsensitive, .diacriticInsensitive]) {
        return String(string[range])
    } else {
        return "Not found"
    }
}
  • Related