How can I remove the whitespace character set from a string but keep the single spaces between words. I would like to remove double spaces and triple spaces, etc...
The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".
strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.
Use the . strip() method to remove whitespace and characters from the beginning and the end of a string. Use the . lstrip() method to remove whitespace and characters only from the beginning of a string.
gsub() function is used to remove the space by removing the space in the given string.
extension String {
func condensingWhitespace() -> String {
return self.components(separatedBy: .whitespacesAndNewlines)
.filter { !$0.isEmpty }
.joined(separator: " ")
}
}
let string = " Lorem \r ipsum dolar sit amet. "
print(string.condensingWhitespace())
// Lorem ipsum dolar sit amet.
NSCharacterSet
makes this easy:
func condenseWhitespace(string: String) -> String {
let components = string.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter({!isEmpty($0)})
return join(" ", components)
}
var string = " Lorem \r ipsum dolar sit amet. "
println(condenseWhitespace(string))
// Lorem ipsum dolar sit amet.
or if you'd like it as a String
extension:
extension String {
func condenseWhitespace() -> String {
let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter({!Swift.isEmpty($0)})
return " ".join(components)
}
}
var string = " Lorem \r ipsum dolar sit amet. "
println(string.condenseWhitespace())
// Lorem ipsum dolar sit amet.
All credit to the NSHipster post on NSCharacterSet.
Swift 2 compatible code:
extension String {
var removeExcessiveSpaces: String {
let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
let filtered = components.filter({!$0.isEmpty})
return filtered.joinWithSeparator(" ")
}
}
Usage:
let str = "test spaces too many"
print(str.removeExcessiveSpaces)
// Output: test spaces too many
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With