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

String 用swift中的单个字符替换字符串中的空格序列,string,swift,replace,String,Swift,Replace,我想用下划线替换字符串中的一系列空格。比如说 "This is a string with a lot of spaces!" 应该成为 "This_is_a_string_with_a_lot_of_spaces!" 如何执行此操作?您可以使用简单的正则表达式替换来执行此操作: let myString = "Alternative non-regex solution: let foo = "This is a string with a lot

我想用下划线替换字符串中的一系列空格。比如说

"This       is     a string with a lot of spaces!"
应该成为

"This_is_a_string_with_a_lot_of_spaces!"

如何执行此操作?

您可以使用简单的正则表达式替换来执行此操作:

let myString = "Alternative non-regex solution:

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! */

let myString=“替代非正则表达式解决方案:

let foo = "@remus suggestion can be simplified (and made Unicode/Emoji/Flag-safe) as

let myString = "  This       is     a string with a lot of spaces! Alternative non-regex, pure Swift (no bridging to 
NSString
) solution:

let spaced = "This       is     a string with a lot of spaces!"

let under = spaced.characters.split(" ", allowEmptySlices: false).map(String.init).joinWithSeparator("_")
也适用于unicode字符(感谢@MartinR提供了这个漂亮的示例)


let foo=“@remus建议可以简化(并使Unicode/Emoji/Flag安全)为


let myString=“这是一个有很多空格的字符串!可选的非正则、纯Swift(不桥接到
NSString
)解决方案:

let foo = "@remus suggestion can be simplified (and made Unicode/Emoji/Flag-safe) as

let myString = "  This       is     a string with a lot of spaces! Alternative non-regex, pure Swift (no bridging to 
NSString
) solution:

let spaced = "This       is     a string with a lot of spaces!"

let under = spaced.characters.split(" ", allowEmptySlices: false).map(String.init).joinWithSeparator("_")
交替,转换时不删除前导空格和尾随空格的交替版本。为简洁起见稍微模糊…;-)


可能有一个更聪明的解决方案涉及到
flatMap()
,但我将把它留给比我更聪明的人!

让myString=“whhhyyyy UNICODE whyyyyy”测试你的代码这是一个非常巧妙的过滤器用法。@NateBirkholz我应该指出,上述方法不会分别替换第一个和最后一个单词之前和之后的空格组;这些空格将被删除(例如,
“这是一个有很多空格的字符串!”
将产生与
“这是一个有很多空格的字符串!”
)相同的结果。这正是我需要的,所以这不会成为问题。请注意,在@dfris解决方案中,这将删除而不是替换初始空格和尾随空格。