删除Swift中String中所有空格\n
和\r
的最有效方法是什么?
我试过了:
for character in string.characters {
}
但这有点不方便。
答案 0 :(得分:57)
let text = "This \n is a st\tri\rng"
let test = String(text.filter { !" \n\t\r".contains($0) })
输出:
print(test) // Thisisastring
虽然Fahri的答案很好,但我更喜欢纯粹的Swift;)
答案 1 :(得分:13)
编辑/更新:
Swift 5或更高版本
我们可以使用新的字符属性isNewline和isWhitespace
extension StringProtocol where Self: RangeReplaceableCollection {
var removingAllWhitespacesAndNewlines: Self {
return filter { !$0.isNewline && !$0.isWhitespace }
}
mutating func removeAllWhitespacesAndNewlines() {
return removeAll { $0.isNewline || $0.isWhitespace }
}
}
let textInput = "Line 1 \n Line 2 \n\r"
let result = textInput.removingAllWhitespacesAndNewlines //"Line1Line2"
var test = "Line 1 \n Line 2 \n\r"
test.removeAllWhitespacesAndNewlines()
print(test) // "Line1Line2"
注意:对于较旧的Swift版本语法,请检查编辑历史记录
答案 2 :(得分:8)
为了完整起见,这是正则表达式版本
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"
答案 3 :(得分:2)
对于Swift 4:
let myString = "This \n is a st\tri\rng"
let trimmedString = myString.components(separatedBy: .whitespacesAndNewlines).joined()
答案 4 :(得分:1)
假设你有这个字符串:“有些单词\ nanother word \ n \ r \ n这里有东西\ t等等\ rmdjsbclsdcbsdilvb \ n \ rand最后这个:)”
这里是如何删除所有可能的空间:
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
如果这回复了您的问题,请告诉我:)
答案 5 :(得分:1)
快捷键4 :
let string = "Test\n with an st\tri\rng"
print(string.components(separatedBy: .whitespacesAndNewlines))
// Result: "Test with an string"
答案 6 :(得分:1)
如果用空格表示空格,请注意,尽管它们看起来相同,但存在多个空格字符。
以下解决方案考虑了这一点:
快捷键5:
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)
答案 7 :(得分:0)
使用此:
let aString: String = "This is my string"
let newString = aString.stringByReplacingOccurrencesOfString(" ", withString: "", options:[], range: nil)
print(newString)
输出: Thisismystring
答案 8 :(得分:0)
如果有人想知道为什么,尽管将“ \ n”和“ \ r”放入集合中,但未从字符串中删除“ \ r \ n”,这是因为swift会处理“ \ r \ n”作为一个字符。
迅速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”并非偶然复制
答案 9 :(得分:-2)
let text = "This \n is a st\tri\rng"
let cleanedText = text.filter { !" \n\t\r".characters.contains($0) }