Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace string into string in Swift? [duplicate]

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.

like image 268
thura oo Avatar asked Jan 15 '15 12:01

thura oo


2 Answers

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")
like image 186
rakeshbs Avatar answered Sep 18 '22 18:09

rakeshbs


You can use stringByReplacingOccurrencesOfString, e.g.

let s1 : String = "Red small car"
let s2 = s1.stringByReplacingOccurrencesOfString("small", withString: "big")
like image 25
Sebastian Dressler Avatar answered Sep 19 '22 18:09

Sebastian Dressler