removeAll()
方法根据给定条件删除字符串中的所有元素。
示例
var string = "Hello World"
// characters to be removed
var text: Set<Character> = ["H", "W"]
// remove "H" and "W" from string
string.removeAll(where: { text.contains($0) })
print(string)
// Output: ello orld
removeAll() 语法
removeAll()
的语法是
string.removeAll(where: condition)
此处,string 是 String
类的一个对象。
removeAll() 参数
removeAll()
方法接受一个参数
- condition - 一个闭包,接受一个条件并返回一个布尔值。如果条件为真,则从 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)
// Output: mv patd Wrds
在上面的示例中,我们创建了一个名为 remove 的集合,其中包含要从字符串 text 中删除的字符。
我们定义了闭包 {remove.contains($0)}
来删除重复的字符。
$0
是一个快捷方式,表示 remove 集合的第一个元素被传递到闭包中。