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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34940044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:37:08  来源:igfitidea点击:

How to remove all the spaces and \n\r in a String?

iosswiftstring

提问by Tauta

What is the most efficient way to remove all the spaces, \nand \rin a String in Swift?

什么是去除所有的空间,最有效的方式\n,并\r在斯威夫特的String?

I have tried:

我试过了:

for character in string.characters {

}

But it's a little inconvenient.

但是有点不方便。

回答by Eendje

Swift 4:

斯威夫特 4:

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

Output:

输出:

let textInput = "Line 1 \n Line 2 \n\r"
let result = textInput.filter { !
extension StringProtocol where Self: RangeReplaceableCollection {
    var removingAllWhitespaces: Self {
        filter { !
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"
.isWhitespace } } mutating func removeAllWhitespaces() { removeAll(where: \.isWhitespace) } }
.isWhitespace } result // "Line1Line2"

While Fahri's answer is nice, I prefer it to be pure Swift ;)

虽然 Fahri 的回答很好,但我更喜欢它是纯 Swift ;)

回答by Leo Dabus

edit/update:

编辑/更新:

Swift 5.2 or later

Swift 5.2 或更高版本

We can use the new Character property isWhitespace

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



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"


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


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

Note: For older Swift versions syntax check edit history

注意:对于较旧的 Swift 版本语法检查编辑历史记录

回答by vadian

For the sake of completeness this is the Regular Expression version

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

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

回答by vadian

For Swift 4:

对于 Swift 4:

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

回答by Haroldo Gondim

Swift 4:

斯威夫特 4

 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)

回答by iAnurag

Use this:

用这个:

let text = "\r\n This \n is a st\tri\rng"
let test = String(text.filter { !"\r\n\n\t\r".contains(
let text = "This \n is a st\tri\rng"
let cleanedText = text.filter { !" \n\t\r".characters.contains(##代码##) }
) })

Output: Thisismystring

输出:Thisismystring

回答by BEN MESSAOUD Mahmoud

Suppose that you have this string : "some words \nanother word\n\r here something \tand something like \rmdjsbclsdcbsdilvb \n\rand finally this :)"

假设你有这个字符串:“一些词\nanother word\n\r 这里的东西\tand 像\rmdjsbclsdcbsdilvb \n\rand 最后这个:)”

here the how to remove all possible space :

这里是如何删除所有可能的空间:

##代码##

Let me know if this respond to your question :)

如果这能回答您的问题,请告诉我:)

回答by Pomeroy

If by spaces you mean whitespaces, be aware that more than one whitespace character exists, although they all look the same.

如果空格是指空格,请注意存在多个空格字符,尽管它们看起来都一样。

The following solution takes that into account:

以下解决方案考虑到了这一点:

Swift 5:

斯威夫特 5:

##代码##

回答by Kamil

If anyone is wondering why, despite of putting "\n" and "\r" into the set, "\r\n" is not removed from the string, it's because "\r\n" is treated by swift as one character.

如果有人想知道为什么尽管将 "\n" 和 "\r" 放入集合中,但 "\r\n" 并未从字符串中删除,这是因为 "\r\n" 被 swift 视为一个字符.

Swift 4:

斯威夫特 4:

##代码##

"\n" is not duplicated by accident

"\n" 不是偶然复制的

回答by tzuer

Swift 4:

斯威夫特 4:

##代码##