是否斯威夫特有一个修剪方法的字符串?例如:
let result = " abc ".trim()
// result == "abc"
是否斯威夫特有一个修剪方法的字符串?例如:
let result = " abc ".trim()
// result == "abc"
当前回答
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
其他回答
你可以在我写的Swift String扩展https://bit.ly/JString中使用trim()方法。
var string = "hello "
var trimmed = string.trim()
println(trimmed)// "hello"
斯威夫特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"
将字符串截断为特定长度
如果你已经输入了一段句子/文本,你想只保存指定长度的文本。将以下扩展添加到类中
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