Swift 字符串 replacingOccurrences()

replacingOccurrences() 方法将字符串中每个匹配的旧字符/文本替换为新字符/文本。

示例

import Foundation
var str1 = "bat ball"

// replace b with c print(str1.replacingOccurrences(of: "b",with: "c"))
// Output: cat call

replacingOccurrences() 语法

replaceOccurrences() 方法的语法是

string.replacingOccurrences(of old: String, with new: String)

此处,stringString 类的一个对象。


replacingOccurrences() 参数

replacingOccurences() 方法可以接受两个参数

  • old - 你要替换的旧子字符串
  • new - 将替换旧子字符串的新子字符串

replacingOccurrences()返回值

  • 返回一个字符串的副本,其中 old 子字符串被替换为 new 子字符串

注意:如果找不到 old 子字符串,它将返回原始字符串的副本。


示例 1:Swift 字符串 replacingOccurrences()

import Foundation 

var text = "Java is awesome. Java is fun."

// all occurrences of "Java" is replaced with "Swift" var new = text.replacingOccurrences(of:"Java", with: "Swift")
print(new)
// "Python" is not the substring of text , so returns original string var new1 = text.replacingOccurrences(of:"Python", with: "Swift")
print(new1)

输出

Swift is awesome. Swift is fun.
Java is awesome. Java is fun.

在此程序中,text.replacingOccurrences(of:"Python", with: "Swift") 返回原始字符串的副本,因为 "Python" 不是 text 的子字符串。


示例 2:将 replacingOccurrences() 用于字符

import Foundation 

var str1 = "abc cba"

// all occurrences of 'a' is replaced with 'z'
print(str1.replacingOccurrences(of: "a", with: "z"))  // zbc cbz

// all occurences of 'L' is replaced with 'J'
print("Lwift".replacingOccurrences(of: "L", with: "S")) // Swift

// "4" not in the string, so returns original string print("Hello".replacingOccurrences(of: "4", with:"J")) // Hello

输出

Swift is awesome. Swift is fun.
Java is awesome. Java is fun.

在此程序中,我们使用了 replacingOccurences() 函数,其中包含:

  • str1 - 一个字符串变量
  • "Lwift""Hello" - 字符串字面量
你觉得这篇文章有帮助吗?

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

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

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