Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove whitespaces in strings in Swift?

This works

let replaced = String(map(aString.generate()) {
    $0 == " " ? "-" : $0 })

and this doesn't

let replaced = String(map(aString.generate()) {
    $0 == " " ? "" : $0 })

Why?

like image 940
Kate Zz Avatar asked Feb 16 '15 19:02

Kate Zz


People also ask

How do I remove Whitespaces from a string?

Use the String. replace() method to remove all whitespace from a string, e.g. str. replace(/\s/g, '') . The replace() method will remove all whitespace characters by replacing them with an empty string.

How do I remove part of a string in Swift?

In the Swift string, we check the removal of a character from the string. To do this task we use the remove() function. This function is used to remove a character from the string. It will return a character that was removed from the given string.

How do I remove special characters from a string in Swift?

Swift String – Remove Specific Characters To remove specific set of characters from a String in Swift, take these characters to be removed in a set, and call the removeAll(where:) method on this string str , with the predicate that if the specific characters contain this character in the String.

How do I remove spaces between words in Swift?

To remove leading and trailing spaces, we use the trimmingCharacters(in:) method that removes all characters in provided character set. In our case, it removes all trailing and leading whitespaces, and new lines.


1 Answers

For Swift 5:

" spaces here ".replacingOccurrences(of: " ", with: "")

returns:

"spaceshere"
like image 66
Shaked Sayag Avatar answered Oct 27 '22 11:10

Shaked Sayag