도래울

Swift string replace 본문

개발/iOS

Swift string replace

도래울 2016. 7. 12. 11:02
let aString: String = "This is my string"
let newString = aString.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.LiteralSearch, range: nil)

And as noted by @cprcrack below, the options and range parameters are optional, so if you don't want to specify string comparison options or a range to do the replacement within, you only need the following.

let aString: String = "This is my string"
let newString = aString.stringByReplacingOccurrencesOfString(" ", withString: "+")

Or, if the data is in a specific format like this, where you're just replacing separation characters, you can use componentsSeparatedByString() to break the string into and array, and then you can use the join function to put them back to together with a specified separator.

let toArray = aString.componentsSeparatedByString(" ")
let backToString = join("+", toArray)

Or if you're looking for a more Swifty solution that doesn't utilize API from NSString, you could use this.

let aString = "Some search text"

let replaced = String(map(aString.generate()) {
    $0 == " " ? "+" : $0
})

If you're using Swift 2, the last two solutions must be written as follows.

let toArray = aString.componentsSeparatedByString(" ")
let backToString = toArray.joinWithSeparator("+")

and

let aString = "Some search text"
let replaced = String(aString.characters.map {
    $0 == " " ? "+" : $0
})


Comments