How to remove spaces from a string in Swift?

I need to remove the leading and trailing spaces around the punctuation character.

For example: Hello , World ... I 'ma newbie iOS Developer.

And I would like to:> Hello, World... I'm a newbie iOS Developer.

How can i do this? I tried to get the components of the string and list it with sentences. But that is not what I need

+5
source share
8 answers

Rob's answer is great, but you can trim it quite a bit using the \p{Po} regex class. Get rid of spaces around punctuation, then replace one regex:

 import Foundation let input = "Hello , World ... I 'ma newbie iOS Developer." let result = input.replacingOccurrences(of: "\\s*(\\p{Po}\\s?)\\s*", with: "$1", options: [.regularExpression]) print(result) // "Hello, World... I'm a newbie iOS Developer." 

Answer Rob is also trying to trim leading / trailing spaces, but your input has none of them. If you take care of this, you can simply call result.trimmingCharacters(in: .whitespacesAndNewlines) as a result.


Here is an explanation of the regular expression. Removing dual screens looks like

 \s*(\p{Po}\s?)\s* 

It consists of the following components:

  • \s* - match zero or more whitespace characters (and throw them away)
  • (…) - Capture the group. Everything that is inside this group is saved by the replacement ( $1 in the replacement belongs to this group).
    • \p{Po} - match a single character in the Unicode category "Other_Punctuation". This includes things like . , ' and but excludes things like ( or - .
    • \s? - Match one optional space character. This saves space after periods (or ellipses).
  • \s* - Once again, match zero or more whitespace characters (and discard them). That's what turns your , World into , World .
+4
source

This is really a wonderful problem and the shame that today it is not easy to do in Swift (someday it will be, but not today).

I hate this code, but I sit on the plane for 20 hours and do not have time to make it more pleasant. At least you can start using NSMutableString . It would be nice to work in String , and Swift hates regular expressions, so this is disgusting, but at least this is the beginning.

 import Foundation let input = "Hello, World ... I 'ma newbie iOS Developer." let adjustments = [ (pattern: "\\s*(\\.\\.\\.|\\.|,)\\s*", replacement: "$1 "), // elipsis or period or comma has trailing space (pattern: "\\s*'\\s*", replacement: "'"), // apostrophe has no extra space (pattern: "^\\s+|\\s+$", replacement: ""), // remove leading or trailing space ] let mutableString = NSMutableString(string: input) for (pattern, replacement) in adjustments { let re = try! NSRegularExpression(pattern: pattern) re.replaceMatches(in: mutableString, options: [], range: NSRange(location: 0, length: mutableString.length), withTemplate: replacement) } mutableString // "Hello, World... I'm a newbie iOS Developer." 

Regular expressions can be very confusing when you first encounter them. A few hints of reading them:

  • The specific language used by the Foundation is described by the ICU .

  • The backslash (\) means that the next character is special for regular expression. But inside the Swift line, a backslash means that the “next character is a special” line. Therefore you need to double them.

  • \ s means "space character"

  • \ s * means zero or more whitespace

  • \ s + means "one or more whitespace characters"

  • $ 1 means "the item we matched in parentheses"

  • | means "or"

  • ^ means "start of line"

  • $ means end of line

  • . means "any character", so to indicate the "actual point" you must enter "\\". in the Swift line.

Please note that I check both "..." and ".". in the same regular expression. You kind of have to do something like this, otherwise "." will match three times in "...". Another approach was to first replace "..." with "..." (a single ellipsis character, typing on a Mac, pressing "Opt-"). Then "..." is a single-character punctuation. (You may also decide to redeploy all the ellipsis to point-to-point at the end of the process.)

Something like this is probably the way I do it in real life, do it and submit, but it can be painful / practice to try to build it like a turn-based state machine, going through one at a time, and tracking the current state.

+3
source

For Swift 3 or 4, you can use:

 let trimmedString = string.trimmingCharacters(in: .whitespaces) 
+3
source

You can try something like string.replacingOccurrences (from: ",", with: ",") for each punctuation ...

0
source

On my phone without a computer, to write you a sample, but if it is always a natural string of the language, and especially if you need to support languages ​​other than English, you can check the NSLinguisticTagger, which has punctuation and space characters

Intro: http://nshipster.com/nslinguistictagger/

Docs: https://developer.apple.com/documentation/foundation/nslinguistictagger

0
source

An interesting problem; here is my hit on the non-regex approach:

 func correct(input: String) -> String { typealias Correction = (punctuation: String, replacement: String) let corrections: [Correction] = [ (punctuation: "...", replacement: "... "), (punctuation: "'", replacement: "'"), (punctuation: ",", replacement: ", "), ] var transformed = input for correction in corrections { transformed = transformed .components(separatedBy: correction.punctuation) .map({ $0.trimmingCharacters(in: .whitespaces) }) .joined(separator: correction.replacement) } return transformed } let testInput = "Hello , World ... I 'ma newbie iOS Developer." let testOutput = correct(input: testInput) // Hello, World... I'm a newbie iOS Developer. 
0
source

If you did this manually while processing arrays of characters, you just would need to check the previous and next characters around the spaces. You can achieve the same result using functional style programming with zip, filter, and map:

 let testInput = "Hello , World ... I 'ma newbie iOS Developer." let punctuation = Set(".\',") let previousNext = zip( [" "] + testInput, String(testInput.dropFirst()) + [" "] ) let filteredChars = zip(Array(previousNext),testInput) .filter{ $1 != " " || !($0.0 != " " && punctuation.contains($0.1)) } let filteredInput = String(filteredChars.map{$1}) print(testInput) // Hello , World ... I 'ma newbie iOS Developer. print(filteredInput) // Hello, World... I'm a newbie iOS Developer. 
0
source

Swift 4, 4.2 and 5

 let str = " Akbar Code " let trimmedString = str.trimmingCharacters(in: .whitespaces) 
-1
source

Source: https://habr.com/ru/post/1272292/


All Articles