I am looking for a way to replace characters in a Swift String
.
Example: \"This is my string\"
I would like to replace \" \" with \"+\" to get \
Swift 4:
let abc = "Hello world"
let result = abc.replacingOccurrences(of: " ", with: "_",
options: NSString.CompareOptions.literal, range:nil)
print(result :\(result))
Output:
result : Hello_world
I think Regex is the most flexible and solid way:
var str = "This is my string"
let regex = try! NSRegularExpression(pattern: " ", options: [])
let output = regex.stringByReplacingMatchesInString(
str,
options: [],
range: NSRange(location: 0, length: str.characters.count),
withTemplate: "+"
)
// output: "This+is+my+string"
This is easy in swift 4.2. just use replacingOccurrences(of: " ", with: "_")
for replace
var myStr = "This is my string"
let replaced = myStr.replacingOccurrences(of: " ", with: "_")
print(replaced)
Swift 3, Swift 4, Swift 5 Solution
let exampleString = "Example string"
//Solution suggested above in Swift 3.0
let stringToArray = exampleString.components(separatedBy: " ")
let stringFromArray = stringToArray.joined(separator: "+")
//Swiftiest solution
let swiftyString = exampleString.replacingOccurrences(of: " ", with: "+")
var str = "This is my string"
print(str.replacingOccurrences(of: " ", with: "+"))
Output is
This+is+my+string
A Swift 3 solution along the lines of Sunkas's:
extension String {
mutating func replace(_ originalString:String, with newString:String) {
self = self.replacingOccurrences(of: originalString, with: newString)
}
}
Use:
var string = "foo!"
string.replace("!", with: "?")
print(string)
Output:
foo?