简体   繁体   English

如何从第一个索引而不是char过滤字符串数组?

[英]How to filter string array from first index rather then containing char?

I have an array of countries. 我有很多国家。 I need to search and update array with searched text but starting with initial char match not anywhere in the string. 我需要使用搜索到的文本来搜索和更新数组,但是要从初始字符匹配开始,而不是字符串中的任何地方。

For eg: If I search in it should return India, Indonesia... not ChINa... 例如:如果我在搜索中返回印度,印度尼西亚...而不是中国...

I have created bleow method which looks into whole string rather then initial char. 我创建了bleow方法,该方法查找整个字符串,而不是初始字符。

Also, I don't have any range in this function so how can I get range from string? 另外,此函数没有任何范围,因此如何从字符串中获取范围?

func searchCountry(for string: String) {
        if !string.isEmpty {
            let filtered = countries?.filter {
                $0.name?.range(of: string,
                               options: .caseInsensitive) != nil
            }
            guard let filteredCountries = filtered else { return }
        }
    }

You can also use this for appropriate output 您也可以将其用于适当的输出

func searchCountry(for string: String?) {
        if let searchText = string {
            let filter = countries.filter({ $0.lowercased().hasPrefix(searchText.lowercased()) })
            print(filter)
        }
    }
 $0.name?.range(of: string,options: [.anchored, .caseInsensitive]) != nil

Use anchored to search the initials. 使用锚定来搜索缩写。 It starts from the start. 它从头开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM