Swift - Replace Character in String
If you want to write this in pure Swift, try:
self.contentLabel.text = Array(myString).reduce("") { $1 == "\\" ? $0 : "\($0)\($1)" }
This is a short hand way of writing:
Array(myString).reduce("", combine: { (inputString, character) -> String in
if character == "\\" {
return inputString
} else {
return "\(inputString)\(character)"
}
})
This converts myString
to an Array
of Character
s, then uses the reduce
function to append them back together into a String
, but substituting an empty string in place of backslashes
Use the following
self.contentLabel.text = content.stringByReplacingOccurrencesOfString("\\", withString: " ", options: NSStringCompareOptions.LiteralSearch, range: nil)