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

后端 未结 27 3359
天命终不由人
天命终不由人 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:04

    string.containsString is only available in 10.10 Yosemite (and probably iOS8). Also bridging it to ObjectiveC crashes in 10.9. You're trying to pass a NSString to NSCFString. I don't know the difference, but I can say 10.9 barfs when it executes this code in a OS X 10.9 app.

    Here are the differences in Swift with 10.9 and 10.10: https://developer.apple.com/library/prerelease/mac/documentation/General/Reference/APIDiffsMacOSX10_10SeedDiff/index.html containsString is only available in 10.10

    Range of String above works great on 10.9. I am finding developing on 10.9 is super stable with Xcode beta2. I don't use playgrounds through or the command line version of playgrounds. I'm finding if the proper frameworks are imported the autocomplete is very helpful.

    0 讨论(0)
  • 2020-11-22 13:06

    You don't need to write any custom code for this. Starting from the 1.2 version Swift has already had all the methods you need:

    • getting string length: count(string);
    • checking if string contains substring: contains(string, substring);
    • checking if string starts with substring: startsWith(string, substring)
    • and etc.
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-11-22 13:07

    If you want to check that one String contains another Sub-String within it or not you can check it like this too,

    var name = String()  
    name = "John has two apples." 
    

    Now, in this particular string if you want to know if it contains fruit name 'apple' or not you can do,

    if name.contains("apple")      
    {  
    print("Yes , it contains fruit name")    
    }    
    else      
    {    
     print(it does not contain any fruit name)    
    }    
    

    Hope this works for you.

    0 讨论(0)
  • 2020-11-22 13:08

    Swift 3: Here you can see my smart search extension fro string that let you make a search on string for seeing if it contains, or maybe to filter a collection based on a search text.

    https://github.com/magonicolas/Swift-Smart-String-Search

    0 讨论(0)
  • 2020-11-22 13:09

    I've found a couple of interesting use cases. These variants make use of the rangeOfString method and I include the equality example to show how one might best use the search and comparison features of Strings in Swift 2.0

    //In viewDidLoad() I assign the current object description (A Swift String) to self.loadedObjectDescription
    self.loadedObjectDescription = self.myObject!.description
    

    Later after I've made changes to self.myObject, I can refer to the following string comparison routines (setup as lazy variables that return a Bool). This allows one to check the state at any time.

    lazy var objectHasChanges : Bool = {
            guard self.myObject != nil else { return false }
            return !(self.loadedObjectDescription == self.myObject!.description)
        }()
    

    A variant of this happens when sometimes I need to analyze a missing property on that object. A string search allows me to find a particular substring being set to nil (the default when an object is created).

        lazy var isMissingProperty : Bool = {
            guard self.myObject != nil else { return true }
            let emptyPropertyValue = "myProperty = nil"
            return (self.myObject!.description.rangeOfString(emptyPropertyValue) != nil) ? true : false
        }()
    
    0 讨论(0)
提交回复
热议问题