— Swift, String, Trimming — 1 min read
Trimming whitespace characters from the beginning or end of a string is a common task in many programming languages, including Swift. Luckily, Swift provides easy-to-use methods to perform this operation.
Swift’s String
class provides two methods to trim a string:
trimmingCharacters(in:)
: Removes characters specified in a given set from the beginning and end of a string.trimmingCharacters(_: CharacterSet)
: Removes the specified characters from the beginning and end of a string.Here's an example usage:
1let str = " Hello, World! "2let trimmedStr1 = str.trimmingCharacters(in: .whitespacesAndNewlines)3let trimmedStr2 = str.trimmingCharacters([" "])4
5print(trimmedStr1) // "Hello, World!"6print(trimmedStr2) // "Hello, World!"
In the above code, trimmedStr1
and trimmedStr2
are both set to "Hello, World!"
, which is the original string with leading and trailing white spaces removed.
In some cases, you may want to remove not only whitespace characters but also other specific characters (such as commas or semicolons) from the beginning and/or end of a string. In such scenarios, regular expressions can be used to define more complex patterns to remove.
Here's an example using regular expressions:
1let str = ",.Hello, World!.,"2let pattern = "^\\W+|\\W+$"3let regex = try! NSRegularExpression(pattern: pattern)4let range = NSRange(location: 0, length: str.utf16.count)5let trimmedStr = regex.stringByReplacingMatches(in: str, options: [], range: range, withTemplate: "")6
7print(trimmedStr) // "Hello, World!"
In the above code, the regular expression pattern ^\\W+|\\W+$
matches one or more non-word characters (\\W
) at the beginning or end of the string (^
and $
indicate the start and end of the string, respectively). The NSRegularExpression
class is used to create a regular expression object from the pattern. The stringByReplacingMatches(in:options:range:withTemplate:)
method is then called on the regular expression object to remove all matches from the original string.
In this article, we learned how to trim text in Swift using built-in string methods and regular expressions. With these tools, you can easily remove unwanted characters from the beginning and/or end of a string to create cleaner, more useful text for your applications.