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

问题描述 投票:20回答:10

删除Swift中String中所有空格\n\r的最有效方法是什么?

我试过了:

for character in string.characters {

}

但这有点不方便。

ios swift string
10个回答
62
投票

斯威夫特4:

let text = "This \n is a st\tri\rng"
let test = String(text.filter { !" \n\t\r".contains($0) })

输出:

print(test) // Thisisastring

虽然Fahri的答案很好,但我更喜欢纯粹的Swift;)


-2
投票

斯威夫特4:

let text = "This \n is a st\tri\rng"
let cleanedText = text.filter { !" \n\t\r".characters.contains($0) }

14
投票

编辑/更新:

Swift 5或更高版本

我们可以使用新的Character属性isNewlineisWhitespace


let textInput = "Line 1 \n Line 2 \n\r"
let result = textInput.filter { !$0.isNewline && !$0.isWhitespace }

result  //  "Line1Line2"

extension StringProtocol where Self: RangeReplaceableCollection {
    var removingAllWhitespacesAndNewlines: Self {
        return filter { !$0.isNewline && !$0.isWhitespace }
    }
    mutating func removeAllWhitespacesAndNewlines() {
        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版本语法检查编辑历史记录


9
投票

为了完整起见,这是正则表达式版本

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"

2
投票

对于Swift 4:

let myString = "This \n is a st\tri\rng"
let trimmedString = myString.components(separatedBy: .whitespacesAndNewlines).joined()

1
投票

假设你有这个字符串:“有些单词\ nanother word \ n \ r \ n这里有点像\ 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

如果这回应你的问题,请告诉我:)


1
投票

斯威夫特4:

let string = "Test\n with an st\tri\rng"
print(string.components(separatedBy: .whitespacesAndNewlines))
// Result: "Test with an string"

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)

0
投票

用这个:

let aString: String = "This is my string"
let newString = aString.stringByReplacingOccurrencesOfString(" ", withString: "", options:[], range: nil)
print(newString)

输出:Thisismystring


0
投票

如果有人想知道为什么,尽管将“\ n”和“\ r”置于集合中,“\ r \ n”不会从字符串中删除,这是因为“\ r \ n”被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”不会意外重复

© www.soinside.com 2019 - 2024. All rights reserved.