swift 在 String 上有修剪方法吗? [英] Does swift have a trim method on String?

查看:34
本文介绍了swift 在 String 上有修剪方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

swift 在 String 上有修剪方法吗?例如:

Does swift have a trim method on String? For example:

let result = " abc ".trim()
// result == "abc"

推荐答案

以下是删除 String 开头和结尾的所有空格的方法.

Here's how you remove all the whitespace from the beginning and end of a String.

(使用 Swift 2.0 测试的示例.)

(Example tested with Swift 2.0.)

let myString = "  \t\t  Let's trim all the whitespace  \n \t  \n  "
let trimmedString = myString.stringByTrimmingCharactersInSet(
    NSCharacterSet.whitespaceAndNewlineCharacterSet()
)
// Returns "Let's trim all the whitespace"

(使用 Swift 3+ 测试的示例.)

(Example tested with Swift 3+.)

let myString = "  \t\t  Let's trim all the whitespace  \n \t  \n  "
let trimmedString = myString.trimmingCharacters(in: .whitespacesAndNewlines)
// Returns "Let's trim all the whitespace"

这篇关于swift 在 String 上有修剪方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆