如何比较两个字符串忽略情况在斯威夫特语言?

在快速忽略情况下,我们如何比较两个字符串? 例如:

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

如果我们比较 var a 和 var b,有没有方法会返回 true

87899 次浏览

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")
}

Could just roll your own:

func equalIgnoringCase(a:String, b:String) -> Bool {
return a.lowercaseString == b.lowercaseString
}
if a.lowercaseString == b.lowercaseString {
//Strings match
}

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")
}

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

Try this :

For older swift:

var a : String = "Cash"
var b : String = "cash"


if(a.caseInsensitiveCompare(b) == NSComparisonResult.OrderedSame){
println("Et voila")
}

Swift 3+

var a : String = "Cash"
var b : String = "cash"
    

if(a.caseInsensitiveCompare(b) == .orderedSame){
print("Et voila")
}

Swift 3

if a.lowercased() == b.lowercased() {


}

Swift 3: You can define your own operator, e.g. ~=.

infix operator ~=


func ~=(lhs: String, rhs: String) -> Bool {
return lhs.caseInsensitiveCompare(rhs) == .orderedSame
}

Which you then can try in a playground

let low = "hej"
let up = "Hej"


func test() {
if low ~= up {
print("same")
} else {
print("not same")
}
}


test() // prints 'same'

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")
}

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
}
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"))

Swift 4, I went the String extension route using caseInsensitiveCompare() as a template (but allowing the operand to be an optional). Here's the playground I used to put it together (new to Swift so feedback more than welcome).

import UIKit


extension String {
func caseInsensitiveEquals<T>(_ otherString: T?) -> Bool where T : StringProtocol {
guard let otherString = otherString else {
return false
}
return self.caseInsensitiveCompare(otherString) == ComparisonResult.orderedSame
}
}


"string 1".caseInsensitiveEquals("string 2") // false


"thingy".caseInsensitiveEquals("thingy") // true


let nilString1: String? = nil
"woohoo".caseInsensitiveEquals(nilString1) // false

localizedCaseInsensitiveContains : Returns whether the receiver contains a given string by performing a case-insensitive, locale-aware search

if a.localizedCaseInsensitiveContains(b) {
//returns true if a contains b (case insensitive)
}

Edited:

caseInsensitiveCompare : Returns the result of invoking compare(_:options:) with NSCaseInsensitiveSearch as the only option.

if a.caseInsensitiveCompare(b) == .orderedSame {
//returns true if a equals b (case insensitive)
}

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")
}

You can just write your String Extension for comparison in just a few line of code

extension String {


func compare(_ with : String)->Bool{
return self.caseInsensitiveCompare(with) == .orderedSame
}
}

For Swift 5 Ignoring the case and compare two string

var a = "cash"
var b = "Cash"
if(a.caseInsensitiveCompare(b) == .orderedSame){
print("Ok")
}