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

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

    SWIFT 4 is very easy!!

    if (yourString.contains("anyThing")) {
       Print("Exist")
    }
    
    0 讨论(0)
  • 2020-11-22 13:16

    In Swift 3

    if((a.range(of: b!, options: String.CompareOptions.caseInsensitive, range: nil, locale: nil)) != nil){
        print("Done")
    }
    
    0 讨论(0)
  • 2020-11-22 13:17

    In Swift 4.2

    Use

    func contains(_ str: String) -> Bool
    

    Example

    let string = "hello Swift"
    let containsSwift = string.contains("Swift")
    print(containsSwift) // prints true
    
    0 讨论(0)
  • 2020-11-22 13:17
    // Search string exist in employee name finding.
    var empName:NSString! = employeeDetails[filterKeyString] as NSString
    
    Case sensitve search.
    let rangeOfSearchString:NSRange! = empName.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch)
    
    // Not found.
    if rangeOfSearchString.location != Foundation.NSNotFound
    {
        // search string not found in employee name.
    }
    // Found
    else
    {
        // search string found in employee name.
    }
    
    0 讨论(0)
  • 2020-11-22 13:18

    Here you go! Ready for Xcode 8 and Swift 3.

    import UIKit
    
    let mString = "This is a String that contains something to search."
    let stringToSearchUpperCase = "String"
    let stringToSearchLowerCase = "string"
    
    mString.contains(stringToSearchUpperCase) //true
    mString.contains(stringToSearchLowerCase) //false
    mString.lowercased().contains(stringToSearchUpperCase) //false
    mString.lowercased().contains(stringToSearchLowerCase) //true
    
    0 讨论(0)
  • 2020-11-22 13:18

    In iOS 8 and newer, you can use these two NSString methods:

    @availability(iOS, introduced=8.0)
    func containsString(aString: String) -> Bool
    
    @availability(iOS, introduced=8.0)
    func localizedCaseInsensitiveContainsString(aString: String) -> Bool
    
    0 讨论(0)
提交回复
热议问题