slo*_*rGJ 1 string replace swift
我想用带下划线的字符串替换一系列空格.例如
"This is a string with a lot of spaces!"
Run Code Online (Sandbox Code Playgroud)
应该成为
"This_is_a_string_with_a_lot_of_spaces!"
Run Code Online (Sandbox Code Playgroud)
这该怎么做?
替代非正则表达式解决方案:
let foo = "This is a string with a lot of spaces!"
let bar = foo
.componentsSeparatedByString(" ")
.filter { !$0.isEmpty }
.joinWithSeparator("_")
print(bar) /* This_is_a_string_with_a_lot_of_spaces! */
Run Code Online (Sandbox Code Playgroud)
也适用于unicode字符(感谢@MartinR这个美丽的例子)
let foo = " "
// ...
/* _____ */
Run Code Online (Sandbox Code Playgroud)
@remus建议可以简化(并使Unicode/Emoji/Flag-safe)为
let myString = " This is a string with a lot of spaces! "
let replacement = myString.stringByReplacingOccurrencesOfString("\\s+", withString: "_", options: .RegularExpressionSearch)
print(replacement)
// _This_is_a_string_with_a_lot_of_spaces!____
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1123 次 |
| 最近记录: |