I've got a problem with removing whitespaces at the beginning and end of string. For e.g. I've got a string like:
\r\n\t- Someone will come here?\n- I don't know for sure...\r\n\r\n
And I need to remove whitespaces only at the end and beginning (string should be look like:
- Someone will come here?\n- I don't know for sure...
Also there could be a lot of variants of string end: "\r\n\r\n", "\r\n", "\n\r\n" and so on...
Thanks.
In this code to restrict Textfield beginning white space
Your string contains not only whitespace but also new line characters.
Use
stringByTrimmingCharactersInSet
withwhitespaceAndNewlineCharacterSet
.In Swift 3 it's more cleaned up:
String trimming first and last whitespaces and newlines in Swift 4+
result: "2 space"
You could first remove from the beginning and then from the end like so:
let string = " exam ple "
let trimmed = string.replacingOccurrences(of: "(^\s+)|(\s+)$", with: "", options: .regularExpression)
print(">" + trimmed3 + "<")
// prints >exam ple<