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

时间:2016-04-01 18:28:58

标签: string swift replace

我想用带下划线的字符串替换一系列空格。例如

"This       is     a string with a lot of spaces!"

应该成为

"This_is_a_string_with_a_lot_of_spaces!"

怎么做?

4 个答案:

答案 0 :(得分: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! */

也适用于unicode字符(感谢@MartinR这个漂亮的例子)

let foo = "       "

// ...

/* _____ */

答案 1 :(得分: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!____

答案 2 :(得分:3)

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

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)
    // "_____"
}

答案 3 :(得分:1)

替代非正则表达式,纯粹的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()的更聪明的解决方案,但我会把它留给比我更聪明的人!