Подтвердить что ты не робот

Как удалить все пробелы и \n\r в String?

Каков наиболее эффективный способ удалить все пробелы, \n и \r в строке в Swift?

Я пробовал:

for character in string.characters {

}

Но это немного неудобно.

4b9b3361

Ответ 1

Swift 4:

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

Вывод:

print(test) // Thisisastring

В то время как ответ Фахри хорош, я предпочитаю, чтобы он был чистым Свифт;)

Ответ 2

редактировать/обновление:

Swift 5 или позже

Мы можем использовать новые свойства символов isNewline и isWhitespace


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 проверьте синтаксис истории изменений.

Ответ 3

Для полноты это версия регулярного выражения

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"

Ответ 4

Для Swift 4:

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

Ответ 5

Предположим, что у вас есть эта строка: "некоторые слова \nother word\n\r здесь что-то\tand что-то вроде \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

Сообщите мне, если это ответит на ваш вопрос:)

Ответ 6

Свифт 4:

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

Ответ 7

Если под пробелами вы подразумеваете пробелы, помните, что существует более одного символа пробела, хотя все они выглядят одинаково.

Следующее решение учитывает это:

Свифт 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)

Ответ 8

Используйте это:

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

Выход: Thisismystring

Ответ 9

Если кому-то интересно, почему, несмотря на то, что в набор введены "\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" не дублируется случайно

Ответ 10

Swift 4:

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