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

57

在Swift中,最高效的去除字符串中所有空格、\n\r的方法是什么?

我已经尝试过:

for character in string.characters {

}

但这有点不方便。

11个回答

99

Swift 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 ;)

我认为对于这个情况来说,filter 太昂贵了, removeSubrangestringByTrimmingCharacters 等方法有什么问题吗? - kakubei
5
removeSubrange 意味着你需要在整个字符串中搜索子串,这会消耗较高的资源,甚至比在移除前进行筛选还要昂贵。stringByTrimmingCharacters 只能删除字符串开头和结尾的空格,不能删除单词之间的空格。 - Kendall Helmstetter Gelner
1
请注意,无需初始化新的字符串。自Swift 4.x起,filter返回一个字符串。https://github.com/apple/swift-evolution/blob/master/proposals/0174-filter-range-replaceable.md - Leo Dabus

68

编辑/更新:

Swift 5.2或更高版本

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


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

result  //  "Line1Line2"

extension StringProtocol where Self: RangeReplaceableCollection {
    var removingAllWhitespaces: Self {
        filter(\.isWhitespace.negated)
    }
    mutating func removeAllWhitespaces() {
        removeAll(where: \.isWhitespace)
    }
}

extension Bool {
    var negated: Bool { !self }
}

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"

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


1
isWhitespace 包括换行符,因此无需再检查 isNewline。 - Wichert Akkerman

27

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

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"

1
谢谢,这对我有帮助。 另外,我想用一个空格来替换所有连续出现的 \n、\r、\t 或空格,所以我使用了 "\s+" 并替换为 " "。let string = "this is an \n \t example" let newString = string.replacingOccurrences(of: "\s+", with: " ", options: .regularExpression) //结果 -> " this is an example" - Chuy47
Swift正则表达式\s是否包含isNewline和isWhitespace的所有内容? - Mike Casan Ballester
1
在大多数正则表达式中,\s 表示空格、制表符、换行符、回车符和换页符 ([ \t\r\n\f]),但不包括 0x2000 范围内的特殊空白字符。 - vadian

7

对于 Swift 4:

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

过滤器太贵了,我认为对于初学者来说,这将更有用。这就是为什么我添加了它。 - user9060380
好的,如果你这么认为那就没问题。但请继续解释你的解决方案。 - L. Guthardt

4
如果你说的空格是指空白字符,那么请注意有不止一个空白字符存在,尽管它们看起来都一样。
下面的解决方案考虑了这一点:
Swift 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)

3
请使用以下内容:
let aString: String = "This is my string"
let newString = aString.stringByReplacingOccurrencesOfString(" ", withString: "", options:[], range: nil)
print(newString)

输出: 这是我的字符串


3
如果有人想知道为什么即使把“\n”和“\r”加入到集合中,“\r\n”仍然没有从字符串中去除,那是因为Swift将“\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"不是无意中重复的

"

2

Swift 4:

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

1
这与问题的要求不符,因为它涉及到去除空格。 - drew..
2
这就像一个字符串数组,它并没有真正解决问题。 - Dasoga

2
假设您有这个字符串:"some words \nanother word\n\r here something \tand something like \rmdjsbclsdcbsdilvb \n\rand finally this :)"。
以下是如何删除所有可能的空格:
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
我只是使用这个:
stringValue.replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "\n", with: "")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接