Replace specific characters in string

随声附和 提交于 2019-12-24 20:40:53

问题


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?


回答1:


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)



回答2:


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


来源:https://stackoverflow.com/questions/54184425/replace-specific-characters-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!