How to compare two strings ignoring case in Swift language?

后端 未结 16 2578
孤街浪徒
孤街浪徒 2020-12-13 05:28

How can we compare two strings in swift ignoring case ? for eg :

var a = \"Cash\"
var b = \"cash\"

Is there any method that will return tru

相关标签:
16条回答
  • 2020-12-13 05:46
    extension String
    {
        func equalIgnoreCase(_ compare:String) -> Bool
        {
            return self.uppercased() == compare.uppercased()
        }
    }
    

    sample of use

    print("lala".equalIgnoreCase("LALA"))
    print("l4la".equalIgnoreCase("LALA"))
    print("laLa".equalIgnoreCase("LALA"))
    print("LALa".equalIgnoreCase("LALA"))
    
    0 讨论(0)
  • 2020-12-13 05:47

    Phone numbers comparison example; using swift 4.2

    var selectPhone = [String]()
    
    if selectPhone.index(where: {$0.caseInsensitiveCompare(contactsList[indexPath.row].phone!) == .orderedSame}) != nil {
        print("Same value")
    } else {
        print("Not the same")
    }
    
    0 讨论(0)
  • 2020-12-13 05:52

    CORRECT WAY:

    let a: String = "Cash"
    let b: String = "cash"
    
    if a.caseInsensitiveCompare(b) == .orderedSame {
        //Strings match 
    }
    

    Please note: ComparisonResult.orderedSame can also be written as .orderedSame in shorthand.

    OTHER WAYS:

    a.

    if a.lowercased() == b.lowercased() {
        //Strings match 
    }
    

    b.

    if a.uppercased() == b.uppercased() {
        //Strings match 
    }
    

    c.

    if a.capitalized() == b.capitalized() {
        //Strings match 
    }
    
    0 讨论(0)
  • 2020-12-13 05:52

    You could also make all the letters uppercase (or lowercase) and see if they are the same.

    var a = “Cash”
    var b = “CASh”
    
    if a.uppercaseString == b.uppercaseString{
      //DO SOMETHING
    }
    

    This will make both variables as ”CASH” and thus they are equal.

    You could also make a String extension

    extension String{
      func equalsIgnoreCase(string:String) -> Bool{
        return self.uppercaseString == string.uppercaseString
      }
    }
    
    if "Something ELSE".equalsIgnoreCase("something Else"){
      print("TRUE")
    }
    
    0 讨论(0)
  • 2020-12-13 05:53

    Try this :

    For older swift:

    var a : String = "Cash"
    var b : String = "cash"
    
    if(a.caseInsensitiveCompare(b) == NSComparisonResult.OrderedSame){
        println("voila")
    }
    

    Swift 3+

    var a : String = "Cash"
    var b : String = "cash"
    
    if(a.caseInsensitiveCompare(b) == .orderedSame){
        print("voila")
    }
    
    0 讨论(0)
  • 2020-12-13 05:53

    Swift 3:

    You can also use the localized case insensitive comparison between two strings function and it returns Bool

    var a = "cash"
    var b = "Cash"
    
    if a.localizedCaseInsensitiveContains(b) {
        print("Identical")           
    } else {
        print("Non Identical")
    }
    
    0 讨论(0)
提交回复
热议问题