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"
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
}
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())
}
}
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