What is the most efficient way to remove all the spaces, \\n
and \\r
in a String in Swift?
I have tried:
for character in s
Swift 4:
let text = "This \n is a st\tri\rng"
let cleanedText = text.filter { !" \n\t\r".characters.contains($0) }
For Swift 4:
let myString = "This \n is a st\tri\rng"
let trimmedString = myString.components(separatedBy: .whitespacesAndNewlines).joined()
For the sake of completeness this is the Regular Expression version
let string = "What is the most efficient way to remove all the spaces and \n \r \tin a String in Swift"
let stringWithoutWhitespace = string.replacingOccurrences(of: "\\s", with: "", options: .regularExpression)
// -> "WhatisthemostefficientwaytoremoveallthespacesandinaStringinSwift"
Suppose that you have this string : "some words \nanother word\n\r here something \tand something like \rmdjsbclsdcbsdilvb \n\rand finally this :)"
here the how to remove all possible space :
let possibleWhiteSpace:NSArray = [" ","\t", "\n\r", "\n","\r"] //here you add other types of white space
var string:NSString = "some words \nanother word\n\r here something \tand something like \rmdjsbclsdcbsdilvb \n\rand finally this :)"
print(string)// initial string with white space
possibleWhiteSpace.enumerateObjectsUsingBlock { (whiteSpace, idx, stop) -> Void in
string = string.stringByReplacingOccurrencesOfString(whiteSpace as! String, withString: "")
}
print(string)//resulting string
Let me know if this respond to your question :)
If anyone is wondering why, despite of putting "\n" and "\r" into the set, "\r\n" is not removed from the string, it's because "\r\n" is treated by swift as one character.
Swift 4:
let text = "\r\n This \n is a st\tri\rng"
let test = String(text.filter { !"\r\n\n\t\r".contains($0) })
"\n" is not duplicated by accident
edit/update:
Swift 5.2 or later
We can use the new Character property isWhitespace
let textInput = "Line 1 \n Line 2 \n\r"
let result = textInput.filter { !$0.isWhitespace }
result // "Line1Line2"
extension StringProtocol where Self: RangeReplaceableCollection {
var removingAllWhitespaces: Self {
filter { !$0.isWhitespace }
}
mutating func removeAllWhitespaces() {
removeAll(where: \.isWhitespace)
}
}
let textInput = "Line 1 \n Line 2 \n\r"
let result = textInput.removingAllWhitespaces //"Line1Line2"
var test = "Line 1 \n Line 2 \n\r"
test.removeAllWhitespaces()
print(test) // "Line1Line2"
Note: For older Swift versions syntax check edit history