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

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

当前回答

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

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

其他回答

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

(用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"
extension String {
    /// EZSE: Trims white space and new line characters
    public mutating func trim() {
         self = self.trimmed()
    }

    /// EZSE: Trims white space and new line characters, returns a new string
    public func trimmed() -> String {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    }
}

从我的这个回购:https://github.com/goktugyil/EZSwiftExtensions/commit/609fce34a41f98733f97dfd7b4c23b5d16416206

我创建了这个函数,允许输入字符串并返回由任意字符修剪的字符串列表

 func Trim(input:String, character:Character)-> [String]
{
    var collection:[String] = [String]()
    var index  = 0
    var copy = input
    let iterable = input
    var trim = input.startIndex.advancedBy(index)

    for i in iterable.characters

    {
        if (i == character)
        {

            trim = input.startIndex.advancedBy(index)
            // apennding to the list
            collection.append(copy.substringToIndex(trim))

            //cut the input
            index += 1
            trim = input.startIndex.advancedBy(index)
            copy = copy.substringFromIndex(trim)

            index = 0
        }
        else
        {
            index += 1
        }
    }
    collection.append(copy)
    return collection

}

As在swift中没有找到这样做的方法(在swift 2.0中编译和工作完美)

斯威夫特3

let result = " abc ".trimmingCharacters(in: .whitespacesAndNewlines)

把这段代码放在你项目的一个文件中,比如Utils.swift:

extension String {   
    func trim() -> String {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
    }
}

所以你可以这样做:

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

Swift 3.0解决方案

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

所以你可以这样做:

let result = " Hello World ".trim()
// result = "HelloWorld"