How to Remove Spaces from a String in Swift

How should I remove all the leading spaces from a string? - swift

To remove leading and trailing whitespaces:

let trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

Swift 3 / Swift 4:

let trimmedString = string.trimmingCharacters(in: .whitespaces)

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

Swift 4:

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

Output:

print(test) // Thisisastring

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

Swift - Remove white spaces from string doesn't work

what do you try to do is

// your input string
let str = "+39 333 3333333"

let arr = str.characters.split(" ").map(String.init) // ["+39", "333", "3333333"]
// remove country code and reconstruct the rest as one string without whitespaces
let str2 = arr.dropFirst().joinWithSeparator("") // "3333333333"

to filter out country code, only if exists (as Eendje asks)

let str = "+39 123 456789"
let arr = str.characters.split(" ").map(String.init)
let str3 = arr.filter { !$0.hasPrefix("+") }.joinWithSeparator("") // "123456789"

UPDATE, based on your update.
160 represents no-breakable space. just modify next line in my code

let arr = str.characters.split{" \u{00A0}".characters.contains($0)}.map(String.init)

there is " \u{00A0}".characters.contains($0) expression where you can extend the string to as much whitespace characters, as you need. 160 is \u{00A0} see details here.

Update for Swift 4

String.characters is deprecated. So the correct answer would now be

// your input string
let str = "+39 333 3333333"

let arr = str.components(separatedBy: .whitespaces) // ["+39", "333", "3333333"]
// remove country code and reconstruct the rest as one string without whitespaces
let str2 = arr.dropFirst().joined() // "3333333333"

removing white spaces at beginning and end of string

Your string contains not only whitespace but also new line characters.

Use stringByTrimmingCharactersInSet with whitespaceAndNewlineCharacterSet.

let string = "\r\n\t- Someone will come here?\n- I don't know for sure...\r\n\r\n"
let trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

In Swift 3 it's more cleaned up:

let trimmedString = string.trimmingCharacters(in: .whitespacesAndNewlines)

How to remove spaces in between from a String in Swift?

var str = "000 111 2222"
let newString = str.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
print(newString)

Swift - iOS: Remove spaces inside a String before or after any special character

You can using regular expression for replace the string with format [ ]+{special_char} and {special_char}[ ]+.

Edit

Update "." to "\\."

Thanks ielyamani

For example

func acceptedAnswer(of answer: String) -> String {
let specialChars = ["/", ":", ",", ";", "-", "\\."]
var newAnswer = answer.trimmingCharacters(in: .whitespacesAndNewlines)
for specialChar in specialChars {
let beforeCharRegex = "[ ]+" + specialChar
let afterCharRegex = specialChar + "[ ]+"
newAnswer = newAnswer.replacingOccurrences(of: beforeCharRegex, with: specialChar, options: .regularExpression, range: nil)
newAnswer = newAnswer.replacingOccurrences(of: afterCharRegex, with: specialChar, options: .regularExpression, range: nil)
}
return newAnswer
}

print(acceptedAnswer(of: " apple / orange : banana "))
// apple/orange:banana

How can I remove some spaces from a string?

Tough, because you don't know the locale of the string. 1234 Euro can be written as € 1,234.00 in English style, or 1.234,00 € in French and German styles. (Euro is very common in England too).

From the limited examples you provided, you can remove the first word, then deleting all spaces, commas, dots and currency signs from the remaining before converting it to Double:

let priceString = "maintenant 2 500,00 €"
let unwanted = " ,.£€₹"
var doubleValue : Double?

if let range = priceString.range(of: " ") {
let chars = priceString[range.upperBound..<priceString.endIndex]
.characters.filter({ !unwanted.characters.contains($0) })
doubleValue = Double(String(chars))
}

// run your asserts here


Related Topics



Leave a reply



Submit