删除所有空格\n
以及\r
Swift中的String中最有效的方法是什么?
我试过了:
for character in string.characters {
}
Run Code Online (Sandbox Code Playgroud)
但这有点不方便.
Een*_*dje 68
斯威夫特4:
let text = "This \n is a st\tri\rng"
let test = String(text.filter { !" \n\t\r".contains($0) })
Run Code Online (Sandbox Code Playgroud)
输出:
print(test) // Thisisastring
Run Code Online (Sandbox Code Playgroud)
虽然Fahri的答案很好,但我更喜欢纯粹的Swift;)
Leo*_*bus 21
您可以使用__CODE__
__CODE__
分解字符串并使用__CODE__
方法将其重新连接回来,如下所示:
let textInput = "Line 1 \n Line 2 \n\r"
let result = textInput.filter { !$0.isNewline && !$0.isWhitespace }
result // "Line1Line2"
Run Code Online (Sandbox Code Playgroud)
您还可以扩展String以使您更容易在代码中的任何位置使用它:
extension StringProtocol where Self: RangeReplaceableCollection {
var removingAllWhitespacesAndNewlines: Self {
return filter { !$0.isNewline && !$0.isWhitespace }
}
mutating func removeAllWhitespacesAndNewlines() {
removeAll { $0.isNewline || $0.isWhitespace }
}
}
Run Code Online (Sandbox Code Playgroud)
编辑/更新:
Swift3或更高版本
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"
Run Code Online (Sandbox Code Playgroud)
let textInput = "Line 1 \n Line 2 \n\r"
let result = textInput.filter { !$0.isNewline && !$0.isWhitespace }
result // "Line1Line2"
Run Code Online (Sandbox Code Playgroud)
vad*_*ian 14
为了完整起见,这是正则表达式版本
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"
Run Code Online (Sandbox Code Playgroud)
小智 8
对于斯威夫特 4:
let myString = "This \n is a st\tri\rng"
let trimmedString = myString.components(separatedBy: .whitespacesAndNewlines).joined()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
29810 次 |
最近记录: |