Check if array contains part of a string in Swift?

前端 未结 9 1054
无人共我
无人共我 2020-12-08 15:04

I have an array containing a number of strings. I have used contains() (see below) to check if a certain string exists in the array however I would like to chec

相关标签:
9条回答
  • 2020-12-08 15:30

    Try like this.

    let itemsArray = ["Google", "Goodbye", "Go", "Hello"]
    let searchToSearch = "go"
    
    let filteredStrings = itemsArray.filter({(item: String) -> Bool in
    
         var stringMatch = item.lowercaseString.rangeOfString(searchToSearch.lowercaseString)
         return stringMatch != nil ? true : false
    })
    

    filteredStrings will contain the list of strings having matched sub strings.

    In Swift Array struct provides filter method, which will filter a provided array based on filtering text criteria.

    0 讨论(0)
  • 2020-12-08 15:30

    MARK:- Swift 5, Swift 4

    //MARK:- You will find the array when its filter in "filteredStrings" variable you can check it by count if count > 0 its means you have find the results
    
    let itemsArray = ["Google", "Goodbye", "Go", "Hello"]
    let searchToSearch = "go"
    
    let filteredStrings = itemsArray.filter({(item: String) -> Bool in
    
        let stringMatch = item.lowercased().range(of: searchToSearch.lowercased())
        return stringMatch != nil ? true : false
    })
    print(filteredStrings)
    
    
    if (filteredStrings as NSArray).count > 0
    {
        //Record found
        //MARK:- You can also print the result and can do any kind of work with them
    }
    else
    {
        //Record Not found
    }
    
    0 讨论(0)
  • 2020-12-08 15:37

    In Swift 4:

        let itemsArray = ["Google", "Goodbye", "Go", "Hello"]
        let searchString = "Go"
        let filterArray = itemsArray.filter({ { $0.range(of: searchString, options: .caseInsensitive) != nil}
        })
        print(filterArray)
    
    0 讨论(0)
提交回复
热议问题