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

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

当前回答

是的,你可以这样做:

var str = "  this is the answer   "
str = str.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
print(srt) // "this is the answer"

CharacterSet实际上是一个非常强大的工具,用于创建修剪规则,比. whitespacesandnewlines等预定义集更灵活。

例如:

var str = " Hello World !"
let cs = CharacterSet.init(charactersIn: " !")
str = str.trimmingCharacters(in: cs)
print(str) // "Hello World"

其他回答

是的,你可以这样做:

var str = "  this is the answer   "
str = str.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
print(srt) // "this is the answer"

CharacterSet实际上是一个非常强大的工具,用于创建修剪规则,比. whitespacesandnewlines等预定义集更灵活。

例如:

var str = " Hello World !"
let cs = CharacterSet.init(charactersIn: " !")
str = str.trimmingCharacters(in: cs)
print(str) // "Hello World"

斯威夫特3

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

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

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: ","))

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

(用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 String扩展https://bit.ly/JString中使用trim()方法。

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