How do I check if a string contains another string in Swift?

后端 未结 27 3358
天命终不由人
天命终不由人 2020-11-22 12:32

In Objective-C the code to check for a substring in an NSString is:

NSString *string = @\"hello Swift\";
NSRange textRange =[strin         


        
27条回答
  •  花落未央
    2020-11-22 13:07

    Another one. Supports case and diacritic options.

    Swift 3.0

    struct MyString {
      static func contains(_ text: String, substring: String,
                           ignoreCase: Bool = true,
                           ignoreDiacritic: Bool = true) -> Bool {
    
        var options = NSString.CompareOptions()
    
        if ignoreCase { _ = options.insert(NSString.CompareOptions.caseInsensitive) }
        if ignoreDiacritic { _ = options.insert(NSString.CompareOptions.diacriticInsensitive) }
    
        return text.range(of: substring, options: options) != nil
      }
    }
    

    Usage

    MyString.contains("Niels Bohr", substring: "Bohr") // true
    

    iOS 9+

    Case and diacritic insensitive function available since iOS 9.

    if #available(iOS 9.0, *) {
      "Für Elise".localizedStandardContains("fur") // true
    }
    

提交回复
热议问题