How to compare two strings ignoring case in Swift language?

后端 未结 16 2579
孤街浪徒
孤街浪徒 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:55

    Try this:

    var a = "Cash"
    var b = "cash"
    let result: NSComparisonResult = a.compare(b, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil)
    
    // You can also ignore last two parameters(thanks 0x7fffffff)
    //let result: NSComparisonResult = a.compare(b, options: NSStringCompareOptions.CaseInsensitiveSearch)
    

    result is type of NSComparisonResult enum:

    enum NSComparisonResult : Int {
    
        case OrderedAscending
        case OrderedSame
        case OrderedDescending
    }
    

    So you can use if statement:

    if result == .OrderedSame {
        println("equal")
    } else {
        println("not equal")
    }
    
    0 讨论(0)
  • 2020-12-13 05:55

    Use caseInsensitiveCompare method:

    let a = "Cash"
    let b = "cash"
    let c = a.caseInsensitiveCompare(b) == .orderedSame
    print(c) // "true"
    

    ComparisonResult tells you which word comes earlier than the other in lexicographic order (i.e. which one comes closer to the front of a dictionary). .orderedSame means the strings would end up in the same spot in the dictionary

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

    Could just roll your own:

    func equalIgnoringCase(a:String, b:String) -> Bool {
        return a.lowercaseString == b.lowercaseString
    }
    
    0 讨论(0)
  • 2020-12-13 06:01

    For Swift 5 Ignoring the case and compare two string

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

    Swift 3

    if a.lowercased() == b.lowercased() {
    
    }
    
    0 讨论(0)
提交回复
热议问题