如何将字符串替换为 Swift 中的字符串?

How to replace string into string in Swift?

我想用另一个字符串替换一个字符串中的一些文本。

例如:字符串等于 "Red small car"。 我想用 "big" 替换 "small" 这样字符串就变成了 "Red big car"。我必须在 swift 中执行此操作。谢谢。

您可以使用stringByReplacingOccurrencesOfString,例如

let s1 : String = "Red small car"
let s2 = s1.stringByReplacingOccurrencesOfString("small", withString: "big")

您可以尝试使用 stringByReplacingOccurrencesOfString

let string = "Big red car"
let replaced = (string as NSString).stringByReplacingOccurrencesOfString("Big", withString: "Small")

编辑 在Swift5

import Foundation

let string = "Big red car"
let replaced = string.replacingOccurrences(of: "Big", with: "Small")