Efficient solution
The following is an efficient solution that replaces the occurrence of an element in array, plus its surrounding spaces, with one space only:
let array = ["one","two","three"]
let str = " eight one four two three five six seven "
var result = ""
var i = str.startIndex
while i < str.endIndex {
var j = i
while j < str.endIndex, str[j] == " " {
j = str.index(after: j)
}
var tempo1 = ""
if i != j { tempo1 += str[i..<j] }
if j < str.endIndex { i = j } else {
result += tempo1
break
}
while j < str.endIndex, str[j] != " " {
j = str.index(after: j)
}
let tempo2 = String(str[i..<j])
if !array.contains(tempo2) {
result += tempo1 + tempo2
}
i = j
}
print(result) //␣␣eight␣four␣five␣␣␣six␣seven␣
The symbol ␣ represents a space.
Benchmarks
Try it online!
Vadian's : 0.000336s
JP Aquino's : 0.000157s
Rob Napier's : 0.000147s
This Solution : 0.000028s
This is at least 5 times faster than any other solution.
Leaving spaces intact
If you don't want to remove spaces (since they're not part of the original array), then this will do:
let array = ["one","two","three"]
let str = "one two three four five six seven "
var result = ""
var i = str.startIndex
while i < str.endIndex {
var j = i
while j < str.endIndex, str[j] == " " {
j = str.index(after: j)
}
if i != j { result += str[i..<j] }
if j < str.endIndex { i = j } else { break }
while j < str.endIndex, str[j] != " " {
j = str.index(after: j)
}
let tempo = String(str[i..<j])
if !array.contains(tempo) {
result += tempo
}
i = j
}
print(result) //␣␣␣four five six seven␣