2016-01-22 13 views

Odpowiedz

30

Swift 4:

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

wyjściowa:

print(test) // Thisisastring 

Chociaż odpowiedź fahri jest ładny, wolę go mieć czysty Swift;)

+0

Myślę, że 'filter' jest za drogi, co jest nie tak z' removeSubrange' lub 'stringByTrimmingCharacters', etc? – kakubei

+0

@kakubei: removeSubrange oznaczałoby, że musisz przeszukać cały ciąg dla podzakresów, które są tak drogie, jak filtrowanie, zanim jeszcze je usuniesz. StringByTrimmingCharacters tylko przycina na początku i końcu łańcucha, a nie w środku pomiędzy słowami. –

0

Użyj tego:

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

Wyjście: Thisismystring

5

Można użyć NSCharacterSetwhitespaceAndNewlineCharacterSet zerwać kryteria wyszukiwania i korzystania joinWithSeparator() metodę łączenia go z powrotem w sposób następujący:

let textInput = "Line 1 \n Line 2 \n\r" 
let whitespaceAndNewlineCharacterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet() 
let components = textInput.componentsSeparatedByCharactersInSet(whitespaceAndNewlineCharacterSet) 
let result = components.joinWithSeparator("") //"Line1Line2" 

Możesz również rozszerzyć String, aby łatwiej można go używać w dowolnym miejscu w kodzie:

extension String { 
    var removingWhitespacesAndNewlines: String { 
     return componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).joinWithSeparator("") 
    } 
} 

edytować/aktualizacji:

Swift3 czy później

let textInput = "Line 1 \n Line 2 \n\r" 
let result = textInput.components(separatedBy: .whitespacesAndNewlines).joined() //"Line1Line2" 

extension String { 
    var removingWhitespacesAndNewlines: String { 
     return components(separatedBy: .whitespacesAndNewlines).joined() 
    } 
} 

let textInput = "Line 1 \n Line 2 \n\r" 
let result = textInput.removingWhitespacesAndNewlines //"Line1Line2" 
1

Załóżmy, że masz ten ciąg: " kilka słów \ nanother słowo \ n \ r tutaj coś \ ti coś jak \ rmdjsbclsdcbsdilvb \ n \ rand w końcu to :) "

tutaj Jak usunąć wszystkie możliwe miejsca:

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 

Daj mi znać, jeśli to odpowiedzieć na Państwa pytanie :)

-1

Swift 4:

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

Dla kompletności wywodu jest to regularna wersja Expression

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" 
+0

Dzięki, to zadziałało dla mnie. Również chciałem zastąpić wszystkie kolejne wystąpienia \ n, \ r, \ t lub spacje pojedynczym odstępem, więc użyłem "\\ s +" i zastąpiłem "". let string = "to jest \ n \ t przykład" let newString = string.replacingOccurrences (of: "\\ s +", with: "", options: .regularExpression) // Wynik -> "to jest przykład " – Chuy47

0

Dla Swift 4:

+0

Istnieje już doskonałe rozwiązanie. –

+0

filtr jest zbyt drogi i myślę, że na początek będą bardziej przydatne. Dlaczego dodałem –

+0

OK, jeśli uważasz, że tak jest dobrze. Ale proszę śmiało wyjaśnić swoje rozwiązanie. –

Powiązane problemy