在Swift中,最高效的去除字符串中所有空格、\n
和\r
的方法是什么?
我已经尝试过:
for character in string.characters {
}
但这有点不方便。
Swift 4:
let text = "This \n is a st\tri\rng"
let test = String(text.filter { !" \n\t\r".contains($0) })
输出:
print(test) // Thisisastring
编辑/更新:
Swift 5.2或更高版本
我们可以使用新的Character属性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(\.isWhitespace.negated)
}
mutating func removeAllWhitespaces() {
removeAll(where: \.isWhitespace)
}
}
extension Bool {
var negated: Bool { !self }
}
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"
注意:对于较旧的Swift版本语法,请检查编辑历史记录
为了完整起见,这是正则表达式版本
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"
\s
是否包含isNewline和isWhitespace的所有内容? - Mike Casan Ballester\s
表示空格、制表符、换行符、回车符和换页符 ([ \t\r\n\f]
),但不包括 0x2000
范围内的特殊空白字符。 - vadian对于 Swift 4:
let myString = "This \n is a st\tri\rng"
let trimmedString = myString.components(separatedBy: .whitespacesAndNewlines).joined()
extension String {
func removingAllWhitespaces() -> String {
return removingCharacters(from: .whitespaces)
}
func removingCharacters(from set: CharacterSet) -> String {
var newString = self
newString.removeAll { char -> Bool in
guard let scalar = char.unicodeScalars.first else { return false }
return set.contains(scalar)
}
return newString
}
}
let noNewlines = "Hello\nWorld".removingCharacters(from: .newlines)
print(noNewlines)
let noWhitespaces = "Hello World".removingCharacters(from: .whitespaces)
print(noWhitespaces)
let aString: String = "This is my string"
let newString = aString.stringByReplacingOccurrencesOfString(" ", withString: "", options:[], range: nil)
print(newString)
输出: 这是我的字符串
let text = "\r\n This \n is a st\tri\rng"
let test = String(text.filter { !"\r\n\n\t\r".contains($0) })
"\n"不是无意中重复的
"Swift 4:
let string = "Test\n with an st\tri\rng"
print(string.components(separatedBy: .whitespacesAndNewlines))
// Result: "Test with an string"
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
stringValue.replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "\n", with: "")
filter
太昂贵了,removeSubrange
或stringByTrimmingCharacters
等方法有什么问题吗? - kakubei