Swift 如何基于排除数组不区分大小写过滤目标字符串数组
你之前的写法var filter = array2.filter({exclude.contains($0)})没有达到预期,是因为这个逻辑是判断array2的元素是否和exclude数组中的某一项完全相等,既没有做子串匹配,也没有处理大小写不敏感的需求。
正确的实现方式如下:
基础实现(满足常规需求)
使用Swift内置的range(of:options:)方法,传入.caseInsensitive参数实现大小写不敏感的子串匹配:
let exclude = ["text 1", "text 2", "APP", "John"] let array2 = ["this is text 1", "This is text 2", "This App is under development", "John is working on this project", "This is great"] let filteredResult = array2.filter { element in // 仅保留不包含任意排除项子串的元素 !exclude.contains { excludeItem in element.range(of: excludeItem, options: .caseInsensitive) != nil } } // 输出:["This is great"] print(filteredResult)
优化实现(大数据量下效率更高)
如果exclude数组元素较多,可以提前把所有排除项转为小写,再统一判断,减少重复计算:
let exclude = ["text 1", "text 2", "APP", "John"] let array2 = ["this is text 1", "This is text 2", "This App is under development", "John is working on this project", "This is great"] // 提前把排除项全部转为小写,只计算一次 let lowercasedExcludes = exclude.map { $0.lowercased() } let filteredResult = array2.filter { element in let lowerElement = element.lowercased() return !lowercasedExcludes.contains { lowerElement.contains($0) } }
内容的提问来源于stack exchange,提问作者snksnk
相关产品推荐
相关产品推荐

