我正在尝试搜索数组中的句子中的关键字。数组的数据来自用户的输入,因此无法知道他们将输入什么内容。我该如何做到这一点,并记住哪些关键词被保存了哪个句子?关键词可以是任何单词,例如(to,the,apache,koala,supercalifragilisticexpialidocious)。我希望计算机能够分开每个句子并尽可能单独检查它们。在数组中搜索关键字中的每个句子 - Swift
func separateAllSentences() {
userInput.enumerateSubstrings(in: userInput.startIndex ..< userInput.endIndex, options: .bySentences) { userInput, _, _, _ in
if let sentence = userInput?.trimmingCharacters(in: .whitespacesAndNewlines), let lastCharacter = sentence.characters.last {
switch lastCharacter {
case ".":
self.statementsArray.append(sentence)
case "?":
self.questionsArray.append(sentence)
default:
self.unknownArray.append(sentence)
}
}
}
print("questions: \(questionsArray)")
print("statements: \(statementsArray)")
print("unknown: \(unknownArray)")
}
没必要用'flatMap(_ :)',因为你申请不返回一个可选或序列变换。只需使用map(_ :)'。 – Hamish
@哈米什,好点! – zepar