我试图用许多与[String]
字符相似的项过滤searchString
。但我想得到的结果是,只返回与searchString
字符长度完全匹配的项,而不返回包含searchString
的所有项。
我尝试了许多选项,包括.map.filter.contains,但无法将该项仅隔离到searchString
。
func filterWaypoint(searchString: String, array: [String]) -> String {
let result = array.filter({(item: String) -> Bool in
let stringMatch = item.localizedLowercase.range(of: searchString.localizedLowercase)
return stringMatch != nil ? true : false
})
print(result)
return result[0]
}
searchString = "POM"
返回:["I JIPOM 384824N 1211336W \'ZOA CA K2 WAYPOIN",
"I JOPOM 441716N 0930727W \'ZMP MN K3 WAYPOIN",
"I POM 340442N 1174713W \'ZLA CA VORTAC",
"I POMBE 353632N 1090611W \'ZAB AZ K2 WAYPOIN",
"I POMDE 293941N 0945039W \'ZHU TX K4 WAYPOIN",
"I POMEE 364451N 1075716W \'ZDV NM K2 REP-PT",
"I POMHO 322104N 0952337W \'ZFW TX K4 WAYPOIN",
"I POMIE 335738N 0810509W \'ZJX SC K7 WAYPOIN".... etc.]
我要返回的项目是上述结果中的第三个项目:
"I POM 340442N 1174713W \'ZLA CA VORTAC"
最佳答案
一个解决方案是使用正则表达式来搜索单词边界
func filterWaypoint(searchString: String, array: [String]) -> String {
let result = array.filter { $0.range(of: "\\b\(searchString)\\b", options: [.regularExpression, .caseInsensitive]) != nil }
print(result)
return result.first ?? ""
}
关于swift - 如何在Swift中将字符串数组过滤为唯一结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57647234/