我想在字符串中找到并替换与数组中任何字符串值匹配的任何单词。我可以使用 .contains(where :
var playersApprovedArray = ["Monica","Zach","Chrissy"]
card.cardText = "Chrissy, do 10 jumping jacks right now!"
if playersApprovedArray.contains(where: card.cardText.contains) {
print("Found matching player in card text")
// Replace the matching word/player here with another word/player
}
但是我不知道如何用数组中的另一个字符串值替换匹配单词的出现。
答案 0 :(得分:0)
这是一个简单的解决方案,可以将一个玩家替换为另一个玩家:
for i in playersApprovedArray.indices {
let player = playersApprovedArray[i]
if let range = cardText.range(of: player) {
let otherIndex = (i + Int.random(in: 1..<playersApprovedArray.count)) % playersApprovedArray.count
let otherPlayer = playersApprovedArray[otherIndex]
cardText.replaceSubrange(range, with: otherPlayer)
break
}
}
如果句子中可能包含更多 players ,则可以删除break
。
这是一个更快的解决方案,它将所有出现的任何玩家姓名都替换为另一个:
let playersApprovedArray = ["Monica","Zach","Chrissy"]
let cardText = " Chrissy, do 10 jumping jacks right now! "
var result = ""
var i = cardText.startIndex
while i < cardText.endIndex {
var j = i
while j < cardText.endIndex,
CharacterSet.letters.inverted.isSuperset(of: CharacterSet(charactersIn: String(cardText[j])))
{
j = cardText.index(after: j)
}
var tempo1 = ""
if i != j { tempo1 += cardText[i..<j] }
if j < cardText.endIndex { i = j } else {
result += tempo1
break
}
while j < cardText.endIndex,
CharacterSet.letters.isSuperset(of: CharacterSet(charactersIn: String(cardText[j])))
{
j = cardText.index(after: j)
}
let tempo2 = String(cardText[i..<j])
if let index = playersApprovedArray.firstIndex(of: tempo2) {
let otherIndex = (index + Int.random(in: 1..<playersApprovedArray.count)) % playersApprovedArray.count
let otherPlayer = playersApprovedArray[otherIndex]
result += tempo1 + otherPlayer
//See comment below for possible early exit
} else {
result += tempo1 + tempo2
}
i = j
}
print(result) // Monica, do 10 jumping jacks right now!
如果您确定字符串中只有一个 player ,那么您可以这样提前退出:
...
result += tempo1 + otherPlayer + cardText[j...]
break
...