0

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.

How can this be implemented?

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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) // _____ __ _____

1 Comment

This is Swift 4. If you are really still using Swift 3 then it would be something like String(s.characters.map { ... })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.