Swift 字符串 replacingOccurrences() 方法
replacingOccurrences()
方法用于将字符串中每个匹配的旧字符/文本替换为新字符/文本。
示例
import Foundation
var str1 = "bat ball"
// 将b替换为c
print(str1.replacingOccurrences(of: "b", with: "c"))
// 输出:cat call
replacingOccurrences()语法
replacingOccurrences()
方法的语法如下:
string.replacingOccurrences(of old: String, with new: String)
这里,string
是String
类的对象。
replacingOccurrences()参数
replacingOccurrences()
方法可以接受两个参数:
- old - 要替换的旧子字符串
- new - 将替换旧子字符串的新子字符串
replacingOccurrences()返回值
- 返回一个字符串的副本,其中
old
子字符串被替换为new
子字符串
注意:如果找不到old
子字符串,则返回原始字符串的副本。
示例1:Swift String replacingOccurrences()
import Foundation
var text = "Java很棒。Java很有趣。"
// 将所有出现的"Java"替换为"Swift"
var new = text.replacingOccurrences(of: "Java", with: "Swift")
print(new)
// "Python"不是文本的子字符串,因此返回原始字符串
var new1 = text.replacingOccurrences(of: "Python", with: "Swift")
print(new1)
输出
Swift很棒。Swift很有趣。
Java很棒。Java很有趣。
在这个程序中,text.replacingOccurrences(of: "Python", with: "Swift")
返回原始字符串的副本,因为"Python"
不是text
的子字符串。
示例2:使用replacingOccurrences()处理字符
import Foundation
var str1 = "abc cba"
// 将所有出现的'a'替换为'z'
print(str1.replacingOccurrences(of: "a", with: "z")) // zbc cbz
// 将所有出现的'L'替换为'J'
print("Lwift".replacingOccurrences(of: "L", with: "S")) // Swift
// 字符串中没有"4",因此返回原始字符串
print("Hello".replacingOccurrences(of: "4", with:"J")) // Hello
输出
zbc cbz
Swift
Hello
在这个程序中,我们使用了replacingOccurrences()
函数处理了:
str1
- 一个字符串变量"Lwift"
和"Hello"
- 字符串字面量