removing white spaces at beginning and end of stri

2020-03-30 03:05发布

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.

8条回答
一纸荒年 Trace。
2楼-- · 2020-03-30 04:06

You can use this extension and just call "yourString".trim()

extension String
{
    func trim() -> String
    {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    }
}
查看更多
贼婆χ
3楼-- · 2020-03-30 04:08

In Swift 4 Use it on any String type variable.

extension String {
    func trimWhiteSpaces() -> String {
        let whiteSpaceSet = NSCharacterSet.whitespaces
        return self.trimmingCharacters(in: whiteSpaceSet)
    }
}

And Call it like this

yourString.trimWhiteSpaces()
查看更多
登录 后发表回答