This question already has an answer here:
这个问题在这里已有答案:
- Any way to replace characters on Swift String? 15 answers
- 有什么方法可以替换Swift String上的字符吗? 15个答案
I want to replace some text in a string with another string.
我想用另一个字符串替换字符串中的一些文本。
For example : A string equals to "Red small car". I want to replace "small" with "big" so the string becomes "Red big car". I have to do this in swift. Thanks.
例如:一个字符串等于“Red small car”。我想用“大”代替“小”,所以字符串变成“红色大车”。我必须迅速做到这一点。谢谢。
2 个解决方案
#1
28
You can try using stringByReplacingOccurrencesOfString
您可以尝试使用stringByReplacingOccurrencesOfString
let string = "Big red car"
let replaced = (string as NSString).stringByReplacingOccurrencesOfString("Big", withString: "Small")
#2
15
You can use stringByReplacingOccurrencesOfString
, e.g.
您可以使用stringByReplacingOccurrencesOfString,例如
let s1 : String = "Red small car"
let s2 = s1.stringByReplacingOccurrencesOfString("small", withString: "big")
#1
28
You can try using stringByReplacingOccurrencesOfString
您可以尝试使用stringByReplacingOccurrencesOfString
let string = "Big red car"
let replaced = (string as NSString).stringByReplacingOccurrencesOfString("Big", withString: "Small")
#2
15
You can use stringByReplacingOccurrencesOfString
, e.g.
您可以使用stringByReplacingOccurrencesOfString,例如
let s1 : String = "Red small car"
let s2 = s1.stringByReplacingOccurrencesOfString("small", withString: "big")