【问题标题】:Check if a string exists in an array case insensitively不区分大小写地检查字符串是否存在于数组中
【发布时间】:2015-09-28 13:00:05
【问题描述】:

声明:

let listArray = ["kashif"]
let word = "kashif"

那么这个

contains(listArray, word) 

返回 true 但如果声明为:

let word = "Kashif"

然后它返回 false,因为比较区分大小写。

如何使这个比较不区分大小写?

【问题讨论】:

    标签: swift contains


    【解决方案1】:

    你可以使用

    word.lowercaseString 
    

    将字符串转换为全小写字符

    【讨论】:

      【解决方案2】:

      试试这个:

      let loword = word.lowercaseString
      let found = contains(listArray) { $0.lowercaseString == loword }
      

      【讨论】:

        【解决方案3】:

        Xcode 8 • Swift 3 或更高版本

        let list = ["kashif"]
        let word = "Kashif"
        
        if list.contains(where: {$0.caseInsensitiveCompare(word) == .orderedSame}) {
            print(true)  // true
        }
        

        或者:

        if list.contains(where: {$0.compare(word, options: .caseInsensitive) == .orderedSame}) {
            print(true)  // true
        }
        

        如果您想知道数组中元素的位置(它可能会找到多个与谓词匹配的元素):

        let indices = list.indices.filter { list[$0].caseInsensitiveCompare(word) == .orderedSame }
        print(indices)  // [0]
        

        您也可以使用localizedStandardContains 方法,该方法不区分大小写和变音符号,并且也可以匹配子字符串:

        func localizedStandardContains<T>(_ string: T) -> Bool where T : StringProtocol
        

        讨论 这是进行用户级字符串搜索的最合适的方法,类似于系统中通常进行的搜索。搜索是区域设置感知的,不区分大小写和变音符号。所应用的搜索选项的确切列表可能会随着时间而改变。

        let list = ["kashif"]
        let word = "Káshif"
        
        if list.contains(where: {$0.localizedStandardContains(word) }) {
            print(true)  // true
        }
        

        【讨论】:

          【解决方案4】:

          我的例子

          func updateSearchResultsForSearchController(searchController: UISearchController) {
              guard let searchText = searchController.searchBar.text else { return }
              let countries = Countries.getAllCountries()
              filteredCountries = countries.filter() {
                  return $0.name.containsString(searchText) || $0.name.lowercaseString.containsString(searchText)
              }
              self.tableView.reloadData()
          }
          

          【讨论】:

            【解决方案5】:

            为了检查一个字符串是否存在于一个数组中(不区分大小写),请使用

            listArray.localizedCaseInsensitiveContainsString(word) 
            

            其中 listArray 是数组的名称 和 word 是您搜索的文本

            此代码适用于 Swift 2.2

            【讨论】:

            • 请编辑更多信息。不建议使用纯代码和“试试这个”的答案,因为它们不包含可搜索的内容,也没有解释为什么有人应该“试试这个”。
            • stackoverflow.com/a/26175437/419348 localizedCaseInsensitiveContainsString 似乎是NSString 中的一种方法。但我不喜欢它的方法签名。也许containsIgnoringCase 是更好的命名方式。
            • @AechoLiu 我更喜欢 containsCaseInsensitive 或 caseInsensitiveContains。顺便说一句,您可以实现自己的stackoverflow.com/a/41232801/2303865
            • @Leo 谢谢你的建议。我现在使用 Swift。我喜欢its naming
            【解决方案6】:

            SWIFT 3.0:

            在字符串数组中查找不区分大小写的字符串很酷,但如果您没有索引,则在某些情况下就不会很酷。

            这是我的解决方案:

            let stringArray = ["FOO", "bar"]()
            if let index = stringArray.index(where: {$0.caseInsensitiveCompare("foo") == .orderedSame}) {
               print("STRING \(stringArray[index]) FOUND AT INDEX \(index)")
               //prints "STRING FOO FOUND AT INDEX 0"                                             
            }
            

            这比其他答案更好 b/c 你在数组中有对象的索引,所以你可以抓住对象并做任何你想做的事情:)

            【讨论】:

            • 请注意,它可能会出现不止一次,这只会为您提供第一个索引。
            【解决方案7】:

            斯威夫特 4

            让所有内容(查询和结果)不区分大小写。

            for item in listArray {
                if item.lowercased().contains(word.lowercased()) {
                    searchResults.append(item)
                }
            }
            

            【讨论】:

            • contains() 应该是 equals(),在这里。
            • 取决于您希望搜索如何工作。对于搜索查询,我更喜欢包含。
            【解决方案8】:

            用于检查字符串是否存在于具有更多选项的数组中(不区分大小写,锚定/搜索仅限于开始)

            使用基金会range(of:options:)

            let list = ["kashif"]
            let word = "Kashif"
            
            
            if list.contains(where: {$0.range(of: word, options: [.caseInsensitive, .anchored]) != nil}) {
                print(true)  // true
            }
            
            if let index = list.index(where: {$0.range(of: word, options: [.caseInsensitive, .anchored]) != nil}) {
                print("Found at index \(index)")  // true
            }
            

            【讨论】:

              【解决方案9】:

              扩展@Govind Kumawat 的回答

              searchStringword 的简单比较是:

              word.range(of: searchString, options: .caseInsensitive) != nil
              

              作为函数:

              func containsCaseInsensitive(searchString: String, in string: String) -> Bool {
                  return string.range(of: searchString, options: .caseInsensitive) != nil
              }
              
              func containsCaseInsensitive(searchString: String, in array: [String]) -> Bool {
                  return array.contains {$0.range(of: searchString, options: .caseInsensitive) != nil}
              }
              
              func caseInsensitiveMatches(searchString: String, in array: [String]) -> [String] {
                  return array.compactMap { string in
                      return string.range(of: searchString, options: .caseInsensitive) != nil
                          ? string
                          : nil
                  }
              }
              

              【讨论】:

                【解决方案10】:

                swift 5,swift 4.2,使用下面的代码。

                let list = ["kAshif"]
                let word = "Kashif"
                
                if list.contains(where: { $0.caseInsensitiveCompare(word) == .orderedSame }) {
                    print("contains is true")
                }
                

                【讨论】:

                  【解决方案11】:

                  你可以添加一个扩展:

                  斯威夫特 5

                  extension Array where Element == String {
                      func containsIgnoringCase(_ element: Element) -> Bool {
                          contains { $0.caseInsensitiveCompare(element) == .orderedSame }
                      }
                  }
                  

                  并像这样使用它:

                  ["tEst"].containsIgnoringCase("TeSt") // true
                  

                  【讨论】:

                    【解决方案12】:

                    如果有人想从模型类中搜索值,比如说

                    struct Country {
                       var name: String
                    }
                    

                    一个大小写不区分大小写的检查,如下所示 -

                    let filteredList = countries.filter({ $0.name.range(of: "searchText", options: .caseInsensitive) != nil })
                    

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 2015-01-17
                      • 2014-09-02
                      • 1970-01-01
                      • 1970-01-01
                      • 2011-08-18
                      • 2015-02-08
                      • 1970-01-01
                      相关资源
                      最近更新 更多