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

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

当前回答

在Swift 3.0中

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

你可以打电话

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

其他回答

Swift 5和4.2

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

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

 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中编译和工作完美)

**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"

您还可以发送您想要修剪的字符

extension String {


    func trim() -> String {

        return self.trimmingCharacters(in: .whitespacesAndNewlines)

    }

    func trim(characterSet:CharacterSet) -> String {

        return self.trimmingCharacters(in: characterSet)

    }
}

validationMessage = validationMessage.trim(characterSet: CharacterSet(charactersIn: ","))

不要忘记导入Foundation或UIKit。

import Foundation
let trimmedString = "   aaa  "".trimmingCharacters(in: .whitespaces)
print(trimmedString)

结果:

"aaa"

否则你会得到:

error: value of type 'String' has no member 'trimmingCharacters'
    return self.trimmingCharacters(in: .whitespaces)