如何删除字符串中的所有空格和\n\r?

Tau*_*uta 27 string ios swift

删除所有空格\n以及\rSwift中的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;)

  • @kakubei:removeSubrange意味着你必须在整个字符串中搜索子范围,在进行任何删除之前已经过滤了.stringByTrimmingCharacters仅在字符串的开头和结尾处修剪,而不是在单词之间的中间修剪. (4认同)

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)