Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing white spaces at beginning and end of string

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.

like image 687
Denis Rumiantsev Avatar asked Nov 28 '22 16:11

Denis Rumiantsev


1 Answers

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)
like image 102
vadian Avatar answered Dec 05 '22 15:12

vadian