是否斯威夫特有一个修剪方法的字符串?例如:
let result = " abc ".trim()
// result == "abc"
是否斯威夫特有一个修剪方法的字符串?例如:
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" */
其他回答
另一种类似的方式:
extension String {
var trimmed:String {
return self.trimmingCharacters(in: CharacterSet.whitespaces)
}
}
使用:
let trimmedString = "myString ".trimmed
斯威夫特3
let result = " abc ".trimmingCharacters(in: .whitespacesAndNewlines)
Swift 5和4.2
let trimmedString = " abc ".trimmingCharacters(in: .whitespaces)
//trimmedString == "abc"
在Swift 3.0中
extension String
{
func trim() -> String
{
return self.trimmingCharacters(in: CharacterSet.whitespaces)
}
}
你可以打电话
let result = " Hello World ".trim() /* result = "Hello World" */
将字符串截断为特定长度
如果你已经输入了一段句子/文本,你想只保存指定长度的文本。将以下扩展添加到类中
extension String {
func trunc(_ length: Int) -> String {
if self.characters.count > length {
return self.substring(to: self.characters.index(self.startIndex, offsetBy: length))
} else {
return self
}
}
func trim() -> String{
return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
Use
var str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
//str is length 74
print(str)
//O/P: Lorem Ipsum is simply dummy text of the printing and typesetting industry.
str = str.trunc(40)
print(str)
//O/P: Lorem Ipsum is simply dummy text of the