我正在嘗試搜索數組中的句子中的關鍵字。數組的數據來自用戶的輸入,因此無法知道他們將輸入什麼內容。我該如何做到這一點,並記住哪些關鍵詞被保存了哪個句子?關鍵詞可以是任何單詞,例如(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