简体   繁体   English

如何在 Swift 语言中比较两个字符串而忽略大小写?

[英]How to compare two strings ignoring case in Swift language?

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 true if we compare var a & var b如果我们比较 var a 和 var b,是否有任何方法会返回 true

Try this :尝试这个 :

For older swift:对于年长的斯威夫特:

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

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

Swift 3+斯威夫特 3+

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

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

Use caseInsensitiveCompare method:使用caseInsensitiveCompare方法:

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 (ie which one comes closer to the front of a dictionary). 比较结果会告诉您哪个词在词典顺序中比另一个词出现得早(即哪个词更靠近字典的前面)。 .orderedSame means the strings would end up in the same spot in the dictionary .orderedSame意味着字符串将在字典中的同一位置结束

if a.lowercaseString == b.lowercaseString {
    //Strings match
}

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:结果是 NSComparisonResult 枚举类型:

enum NSComparisonResult : Int {

    case OrderedAscending
    case OrderedSame
    case OrderedDescending
}

So you can use if statement:所以你可以使用 if 语句:

if result == .OrderedSame {
    println("equal")
} else {
    println("not equal")
}

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.请注意: ComparisonResult.orderedSame 也可以简写为 .orderedSame。

OTHER WAYS:其他方法:

a.一种。

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

b.

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

c. C。

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

localizedCaseInsensitiveContains : Returns whether the receiver contains a given string by performing a case-insensitive, locale-aware search localizedCaseInsensitiveContains :通过执行不区分大小写的区域设置搜索来返回接收器是否包含给定的字符串

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. caseInsensitiveCompare :返回调用 compare(_:options:) 的结果,其中 NSCaseInsensitiveSearch 作为唯一选项。

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

Could just roll your own:可以自己推出:

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

Phone numbers comparison example;电话号码比较示例; using swift 4.2使用 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 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.这将使两个变量都为”CASH” ,因此它们是相等的。

You could also make a String extension你也可以做一个String扩展

extension String{
  func equalsIgnoreCase(string:String) -> Bool{
    return self.uppercaseString == string.uppercaseString
  }
}

if "Something ELSE".equalsIgnoreCase("something Else"){
  print("TRUE")
}

Swift 4, I went the String extension route using caseInsensitiveCompare() as a template (but allowing the operand to be an optional). Swift 4,我使用 caseInsensitiveCompare() 作为模板(但允许操作数是可选的)使用 String 扩展路由。 Here's the playground I used to put it together (new to Swift so feedback more than welcome).这是我曾经把它放在一起的游乐场(对 Swift 来说是新的,所以非常欢迎反馈)。

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

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对于 Swift 5 忽略大小写并比较两个字符串

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

Swift 3 : You can define your own operator, eg ~= . Swift 3 :您可以定义自己的运算符,例如~=

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斯威夫特 3

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

}
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 3:斯威夫特 3:

You can also use the localized case insensitive comparison between two strings function and it returns Bool您还可以在两个字符串函数之间使用本地化不区分大小写的比较,它返回Bool

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

if a.localizedCaseInsensitiveContains(b) {
    print("Identical")           
} else {
    print("Non Identical")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM