删除前导和尾随的 WhiteSpace 和 NewLine

Version < 3.0

let someString = "  Swift Language  \n"
let trimmedString = someString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
// "Swift Language"

方法 stringByTrimmingCharactersInSet 返回一个新字符串,该字符串是通过从给定字符集中包含的 String 字符的两端删除而生成的。

我们也可以只删除空格或换行符。

仅删除空格:

let trimmedWhiteSpace = someString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// "Swift Language  \n"

仅删除换行符:

let trimmedNewLine = someString.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())
// "  Swift Language  "

Version = 3.0

let someString = "  Swift Language  \n"

let trimmedString = someString.trimmingCharacters(in: .whitespacesAndNewlines)
// "Swift Language"

let trimmedWhiteSpace = someString.trimmingCharacters(in: .whitespaces)
// "Swift Language  \n"

let trimmedNewLine = someString.trimmingCharacters(in: .newlines)
// "  Swift Language  "

注意:所有这些方法都属于 Foundation。如果尚未通过 Cocoa 或 UIKit 等其他库导入 Foundation,请使用 import Foundation