【发布时间】:2016-04-01 18:28:58
【问题描述】:
我想用下划线替换字符串中的一系列空格。例如
"This is a string with a lot of spaces!"
应该变成
"This_is_a_string_with_a_lot_of_spaces!"
如何做到这一点?
【问题讨论】:
我想用下划线替换字符串中的一系列空格。例如
"This is a string with a lot of spaces!"
应该变成
"This_is_a_string_with_a_lot_of_spaces!"
如何做到这一点?
【问题讨论】:
替代的非正则表达式解决方案:
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! */
也适用于 unicode 字符(感谢@MartinR 提供了这个漂亮的示例)
let foo = "?? ?? ? ?? ? ?"
// ...
/* ??_??_?_??_?_? */
【讨论】:
" This is a string with a lot of spaces! " 将产生与"This is a string with a lot of spaces!" 相同的结果)。
@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!_??_??_??_
【讨论】:
您可以使用简单的正则表达式替换来做到这一点:
let myString = "?? ?? ? ?? ? ?"
if let regex = try? NSRegularExpression(pattern: "\\s+", options: []) {
let replacement = regex.stringByReplacingMatchesInString(myString, options: .WithTransparentBounds, range: NSMakeRange(0, (myString as NSString).length), withTemplate: "_")
print(replacement)
// "??_??_?_??_?_?"
}
【讨论】:
let myString = "?? ?? ? ?? ? ?" 测试您的代码 ... :)
替代的非正则表达式,纯 Swift(没有桥接到NSString)解决方案:
let spaced = "This is a string with a lot of spaces!"
let under = spaced.characters.split(" ", allowEmptySlices: false).map(String.init).joinWithSeparator("_")
转换时不删除前导和尾随空格的替代版本。为简洁起见,稍微混淆了... ;-)
let reduced = String(spaced.characters.reduce([Character]()) { let n = $1 == " " ? "_" : $1; var o = $0; o.append(n); guard let e = $0.last else { return o }; return e == "_" && n == "_" ? $0 : o })
可能有一个更聪明的解决方案涉及flatMap(),但我会把它留给比我更聪明的人!
【讨论】: