是否斯威夫特有一个修剪方法的字符串?例如:

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

当前回答

Swift 5和4.2

let trimmedString = " abc ".trimmingCharacters(in: .whitespaces)
 //trimmedString == "abc"

其他回答

下面介绍如何从字符串的开头和结尾删除所有空白。

(用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+测试的示例。)

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 4.0删除空格和新行

extension String {
    func trim() -> String {
        return self.trimmingCharacters(in: .whitespacesAndNewlines)         
    }
}
**Swift 5**

extension String {

    func trimAllSpace() -> String {
         return components(separatedBy: .whitespacesAndNewlines).joined()
    }
    
    func trimSpace() -> String {
        return self.trimmingCharacters(in: .whitespacesAndNewlines)
    }
}

**Use:**
let result = " abc ".trimAllSpace()
// result == "abc"
let ex = " abc cd  ".trimSpace()
// ex == "abc cd"

在Swift3 XCode 8 Final中

注意CharacterSet。空格不再是函数了!

(NSCharacterSet.whitespaces也不是)

extension String {
    func trim() -> String {
        return self.trimmingCharacters(in: CharacterSet.whitespaces)
    }
}

你可以在我写的Swift String扩展https://bit.ly/JString中使用trim()方法。

var string = "hello  "
var trimmed = string.trim()
println(trimmed)// "hello"