Search code examples
iosstringswiftwhitespacetrim

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.


Solution

  • 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)