用swift中的单个字符替换字符串中的空格序列

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)

这该怎么做?

dfr*_*fri 7

替代非正则表达式解决方案:

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)

  • @NateBirkholz 但是,我应该指出,上面的方法不会分别替换第一个和最后一个单词之前和之后的空格组;这些空格将被删除(例如“这是一个有很多空格的字符串!”将产生与“这是一个有很多空格的字符串!”相同的结果)。 (2认同)

Mar*_*n R 5

@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)