Swift 对字符串有修剪方法吗?例如:

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

推荐答案

下面是如何删除String开头和结尾的所有空格.

(Example tested with 100.)

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"

(Example tested with 100.)

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相关问答推荐

自定义完整屏幕封面动画

Swift-Can无法在AudioKit中找出简单的麦克风效果-文件链

了解SWIFT中的任务行为

查找数组中 ** 元素 ** 的属性的最小值和最大值

String.Index encodedOffset已弃用,但建议的替代方案不起作用

Result类型的初始值设定项失败?

使用 @resultBuilder 的通用 buildList 函数

如何使 onKeyPress 与 TextField 快速配合使用?

为什么自定义串行队列的目标是全局队列时,Swift中不会并发执行?

如何删除快速处理消息

为 ObservedObject 和 State 对象配置预览

MacOS KIND 是如何实现的

Swift-如何接受多个(联合)类型作为参数

用户输入以更改通过点击生成的形状大小

令人满意的 var body:协议扩展中的一些视图

无法分配给属性:absoluteString是一个只能获取的属性

Xcode 13.3 将函数调用更改为属性访问

如何从 Swift 中的字符串生成条形码?

UICollectionView 自定义单元格在 Swift 中填充宽度

如何以编程方式读取 wkwebview 的控制台日志(log)