我有一个字符串数组,其中包含用户输入的值。我有一个包含几个单词的字符串(字符串中的单词数是不同的)。每当字符串中的一个单词与数组中的一个单词匹配时,我都想增加一个Int。
我用的是这个方法:
var searchWordsArr: [String] = [] \\filled by user input
var message: String = "" \\random number of words
var numRelevantWords = 0
var i = 0
while i < self.searchWordsArr.count {
i+=1
if message.contains(self.searchWordsArr[i-1]) {
numRelevantWords += 1
}
}在我的第一个示例中,字符串包含25个单词,数组包含3个单词。这三个字在字符串中总共出现了12次。用上述方法测得numRelevantWords值为2。
发布于 2017-05-11 21:53:50
我会用regex。不久的将来,Swift将有本机正则表达式。但在此之前,你必须求助于基金会:
let words = ["the", "cat", "sat"]
let input = "The cat sat on the mat and the mat sat on the catastrophe"
var result = 0
let pattern = "\\b(" + words.joined(separator:"|") + ")\\b"
do {
let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let match = regex.matches(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count))
result += match.count // 7, that's your answer
} catch {
print("illegal regex")
}发布于 2017-05-11 18:58:44
将它们添加到NSCountedSet中:
let searchWords = NSCountedSet()
searchWords.add("Bob")
searchWords.add("John")
searchWords.add("Bob")
print(searchWords.count(for: "Bob")) // 2发布于 2017-05-11 19:25:19
“纯”斯威夫特(无基金会)
let message = "aa bb aaaa ab ac aa aa"
let words = message.characters.split(separator: " ").map(String.init)
let search:Set = ["aa", "bb", "aa"]
let found = words.reduce(0) { (i, word) -> Int in
var i = i
i += search.contains(word) ? 1 : 0
return i
}
print(found, "word(s) from the message are in the search set")版画
4 word(s) from the the message are in the search set更新(见讨论)
使用集
var search: Set<String> = [] // an empty set with Element == String
search.insert("aa") // insert word to set 使用阵列
var search: Array<String> = [] // an empty array
search.append("aa") // append word to array也许你是在找
let message = "the cat in the hat"
let words = message.characters.split(separator: " ").map(String.init)
let search:Set = ["aa", "bb", "pppp", "the"]
let found = search.reduce(0) { (i, word) -> Int in
var i = i
i += words.contains(word) ? 1 : 0
return i
}
print(found, "word(s) from the search set found in the message")版画
1 word(s) from the search set found in the message如果你想提供与接受的答案相同的答案
let words = ["the", "cat", "sat"]
let input = "The cat sat on the mat and the mat sat on the catastrophe"
let inputWords = input.lowercased().characters.split(separator: " ").map(String.init)
let found = inputWords.reduce(0) { (i, word) -> Int in
var i = i
i += words.contains(word.lowercased()) ? 1 : 0
return i
}
print(found, "word(s) from the search set found in the message")版画
7 word(s) from the search set found in the messagehttps://stackoverflow.com/questions/43923479
复制相似问题