跳到主要内容

Swift 字符串 removeAll() 方法

removeAll() 方法根据给定条件从字符串中移除所有元素。

示例

var string = "Hello World"

// 要移除的字符
var text: Set<Character> = ["H", "W"]

// 从字符串中移除 "H" 和 "W"
string.removeAll(where: { text.contains($0) })

print(string)

// 输出: ello orld

removeAll() 语法

removeAll() 的语法如下:

string.removeAll(where: condition)

这里,stringString 类的一个对象。

removeAll() 参数

removeAll() 方法接受一个参数:

  • condition - 一个接受条件并返回 bool 值的闭包。如果条件为 true,则从 string 中移除指定的字符。

removeAll() 返回值

removeAll() 方法不返回任何值。它只从字符串中移除字符。

示例:Swift removeAll()

var text = "Remove Repeated Words"

let remove: Set<Character> = ["e", "R", "o", "S"]

text.removeAll(where: { remove.contains($0) })

print(text)

// 输出: mv patd Wrds

在上面的示例中,我们创建了一个名为 remove 的集合,其中包含要从字符串 text 中移除的字符。

我们定义了闭包 {remove.contains($0)} 来移除重复的字符。

$0 是指第一个元素被传递到闭包中的缩写形式。