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.
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.
You can try using stringByReplacingOccurrencesOfString
let string = "Big red car"
let replaced = (string as NSString).stringByReplacingOccurrencesOfString("Big", withString: "Small")
Edit In Swift 5
import Foundation
let string = "Big red car"
let replaced = string.replacingOccurrences(of: "Big", with: "Small")
error: cannot invoke 'stringByReplacingOccurrencesOfString' with an argument list of type '(StringLiteralConvertible, withString: StringLiteralConvertible)', w.o. the cast, it works.import Foundation. – Anyway, this question has already been asked and answered (probably more than once).Foundation. Very strange...let replaced = string.replacingOccurrences(of:"Big" with "Small")let replaced = string.replacingOccurrences(of:"Big", with:"Small")You can use stringByReplacingOccurrencesOfString, e.g.
let s1 : String = "Red small car"
let s2 = s1.stringByReplacingOccurrencesOfString("small", withString: "big")