最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]swift字符串只去除最开始和末尾的回车换行

Swift crifan 4112浏览 0评论

想要实现在输入字符串的时候,过滤掉空白的内容:

回车

换行

空格

然后用:

    //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字符串只去除最开始和末尾的回车换行

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.163 seconds, using 22.12MB memory