根据数组中的值替换字符串中的多个单词

时间:2019-03-19 19:34:51

标签: swift string

我有一个字符串数组和另一个字符串:

@PreDestroy

从字符串中删除数组中出现的事件的快速方法是什么?我尝试了for循环,但想看看在这种情况下过滤器是否可以工作?

4 个答案:

答案 0 :(得分:3)

我相信您正在考虑的filter表达式是这样的:

let finalString = string
    .split(separator: " ")  // Split them
    .lazy                   // Maybe it's very long, and we don't want intermediates
    .map(String.init)       // Convert to the same type as array
    .filter { !array.contains($0) } // Filter
    .joined(separator: " ") // Put them back together

答案 1 :(得分:2)

在Swift 4.2中,有一个removeAll(where: API。

let array = ["one","two","three"]
let string = "one two three four five six seven"

var components = string.components(separatedBy: " ")
components.removeAll{array.contains($0)}
let result = components.joined(separator: " ") // "four five six seven"

答案 2 :(得分:1)

有效的解决方案

以下是一种有效的解决方案,它仅用一个空格替换array中某个元素的出现及其周围的空格:

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␣

符号代表一个空格。


基准

Try it online!

Vadian's      : 0.000336s
JP Aquino's   : 0.000157s
Rob Napier's  : 0.000147s
This Solution : 0.000028s

这比任何其他解决方案至少快5倍。


保留空格

如果您不想删除空格(因为它们不属于原始数组),则可以这样做:

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␣

答案 3 :(得分:0)

let array = ["one","two","three"]
let string = "one two three four five six seven"

//Convert string to array
var stringArray  = string.components(separatedBy: " ")

//Remove elements from original array
stringArray = stringArray.filter { !array.contains($0) }

//Convert stringArray back to string
let finalString = stringArray.joined(separator: " ")
print(finalString)// prints "four five six seven"