Reputation: 385
I want to replace a series of spaces from a string with an underscore. For example
"This is a string with a lot of spaces!"
should become
"This_is_a_string_with_a_lot_of_spaces!"
How to do this?
Upvotes: 3
Views: 2341
Reputation:
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("_")
Alternate, alternate version that doesn't remove leading and trailing spaces when converting. Slightly obfuscated for brevity... ;-)
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 })
There's probably a more clever solution involving flatMap()
but I'll leave it to someone more clever than I!
Upvotes: 1
Reputation: 72905
You can use a simple regular expression replacement to do this:
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)
// "😀😬_😁😀_😬_😁😀_😬_😁"
}
Upvotes: 3
Reputation: 539795
@remus suggestion can be simplified (and made Unicode/Emoji/Flag-safe) as
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!_😀😬_🇨🇦_🇨🇰_
Upvotes: 6
Reputation: 73186
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! */
Works also for unicode characters (thanks @MartinR for this beautiful example)
let foo = "😀😬 😁😀 😬 😁😀 😬 😁"
// ...
/* 😀😬_😁😀_😬_😁😀_😬_😁 */
Upvotes: 12