替换 Swift 中字符串中的特定字符
Replace specific characters in string in Swift
我目前正在尝试使用 Swift 3.
替换字符串中的特定字符
var str = "Hello"
var replace = str.replacingOccurrences(of: "Hello", with: "_____")
print(replace)
这将打印:_____ 但是当 str 发生变化并且由不同数量的字符或几个单词组成时,我的问题就出现了,例如:
var str = "Hello World"
现在我希望替换变量在 str
更改时自动更新。除 'Space' 之外的所有字符都应替换为 _ ,然后打印 _____ _____ 应该代表 Hello World.
如何实施?
All characters except 'Space' should be replaced with _
有几个选项。您可以 map()
每个字符对其进行替换,并将结果组合成一个字符串:
let s = "Swift is great"
let t = String(s.map { [=10=] == " " ? [=10=] : "_" })
print(t) // _____ __ _____
或者使用正则表达式,\S
是“非空白字符”的模式:
let t = s.replacingOccurrences(of: "\S", with: "_", options: .regularExpression)
print(t) // _____ __ _____
如果要替换所有单词字符,可以使用之前使用的相同函数的options
参数的regularExpressions
输入,只需将具体的String输入更改为\w
,这将匹配任何单词字符。
let str = "Hello World"
let replace = str.replacingOccurrences(of: "\w", with: "_", options: .regularExpression) // "_____ _____"
请记住,\w
也不会替换其他特殊字符,因此对于 "Hello World!"
的输入,它将生成 "_____ _____!"
。如果要替换除空格以外的所有字符,请使用 \S
.
let replace = str.replacingOccurrences(of: "\S", with: "_", options: .regularExpression)
我目前正在尝试使用 Swift 3.
替换字符串中的特定字符var str = "Hello"
var replace = str.replacingOccurrences(of: "Hello", with: "_____")
print(replace)
这将打印:_____ 但是当 str 发生变化并且由不同数量的字符或几个单词组成时,我的问题就出现了,例如:
var str = "Hello World"
现在我希望替换变量在 str
更改时自动更新。除 'Space' 之外的所有字符都应替换为 _ ,然后打印 _____ _____ 应该代表 Hello World.
如何实施?
All characters except 'Space' should be replaced with _
有几个选项。您可以 map()
每个字符对其进行替换,并将结果组合成一个字符串:
let s = "Swift is great"
let t = String(s.map { [=10=] == " " ? [=10=] : "_" })
print(t) // _____ __ _____
或者使用正则表达式,\S
是“非空白字符”的模式:
let t = s.replacingOccurrences(of: "\S", with: "_", options: .regularExpression)
print(t) // _____ __ _____
如果要替换所有单词字符,可以使用之前使用的相同函数的options
参数的regularExpressions
输入,只需将具体的String输入更改为\w
,这将匹配任何单词字符。
let str = "Hello World"
let replace = str.replacingOccurrences(of: "\w", with: "_", options: .regularExpression) // "_____ _____"
请记住,\w
也不会替换其他特殊字符,因此对于 "Hello World!"
的输入,它将生成 "_____ _____!"
。如果要替换除空格以外的所有字符,请使用 \S
.
let replace = str.replacingOccurrences(of: "\S", with: "_", options: .regularExpression)