想要实现在输入字符串的时候,过滤掉空白的内容:
回车
换行
空格
然后用:
//Trims white space and new line characters, returns a new string func trim() -> String { return self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).joinWithSeparator("") } |
结果却把:
文字中间的,正常的换行,都去掉了。。。
所以要重新去实现。
swift string remove leading and trailing white space
Does swift has trim method on String? – Stack Overflow
how should I remove all the spaces from a string? – swift – Stack Overflow
//Trims white space and new line characters, returns a new string func trim() -> String { // return self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).joinWithSeparator("") //return stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) return stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } |
效果:
[总结]
swift中string执行trim,只去除最开始和最末尾的白空格(回车,换行,空格,其他特殊空格),则可以:
yourStr.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
即可。
转载请注明:在路上 » [已解决]swift字符串只去除最开始和末尾的回车换行