I am currently trying to replace specific characters in a string using Swift 3.
var str = "Hello"
var replace = str.replacingOccurrences(of: "Hello", with: "_____")
print(replace)
This will print: _____ but my problem occurs when str changes and consists of a different number of characters or several words such as:
var str = "Hello World"
Now I want the replace variable to update automatically when str
is changed. All characters except 'Space' should be replaced with _ and later print _____ _____ which is supposed to represent Hello World.
Any thought of how this can be implemented?
If you want to replace all word characters, you can use the regularExpressions
input to the options
parameter of the same function you were using before, just change the specific String input to \\w
, which will match any word characters.
let str = "Hello World"
let replace = str.replacingOccurrences(of: "\\w", with: "_", options: .regularExpression) // "_____ _____"
Bear in mind that the \\w
won't replace other special characters either, so for an input of "Hello World!"
, it will produce "_____ _____!"
. If you want to replace every character but whitespaces, use \\S
.
let replace = str.replacingOccurrences(of: "\\S", with: "_", options: .regularExpression)
All characters except 'Space' should be replaced with _
There are several options. You can map()
each character to its replacement, and combine the result to a string:
let s = "Swift is great"
let t = String(s.map { $0 == " " ? $0 : "_" })
print(t) // _____ __ _____
Or use regular expressions, \S
is the pattern for “not a whitespace character”:
let t = s.replacingOccurrences(of: "\\S", with: "_", options: .regularExpression)
print(t) // _____ __ _____