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

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"

其他回答

斯威夫特3

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

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

(用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 5和4.2

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

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

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

是的,你可以这样做:

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"