Swift String removeAll()

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)

此处,stringString 类的一个对象。


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 集合的第一个元素被传递到闭包中。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战