刪除前導和尾隨的 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