Does swift have a trim method on String? For example:
let result = " abc ".trim()
// result == "abc"
Here's how you remove all the whitespace from the beginning and end of a String
.
(Example tested with 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"
(Example tested with 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"
Put this code on a file on your project, something likes Utils.swift:
extension String {
func trim() -> String {
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
}
So you will be able to do this:
let result = " abc ".trim()
// result == "abc"
Swift 3.0 Solution
extension String {
func trim() -> String {
return self.trimmingCharacters(in: NSCharacterSet.whitespaces)
}
}
So you will be able to do this:
let result = " Hello World ".trim()
// result = "HelloWorld"
In Swift 3.0
extension String
{
func trim() -> String
{
return self.trimmingCharacters(in: CharacterSet.whitespaces)
}
}
And you can call
let result = " Hello World ".trim() /* result = "Hello World" */
let trimmedString = " abc ".trimmingCharacters(in: .whitespaces)
//trimmedString == "abc"
let result = " abc ".trimmingCharacters(in: .whitespacesAndNewlines)
Yes it has, you can do it like this:
var str = " this is the answer "
str = str.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
print(srt) // "this is the answer"
CharacterSet is actually a really powerful tool to create a trim rule with much more flexibility than a pre defined set like .whitespacesAndNewlines has.
For Example:
var str = " Hello World !"
let cs = CharacterSet.init(charactersIn: " !")
str = str.trimmingCharacters(in: cs)
print(str) // "Hello World"
Truncate String to Specific Length
If you have entered block of sentence/text and you want to save only specified length out of it text. Add the following extension to Class
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
//Swift 4.0 Remove spaces and new lines
extension String {
func trim() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
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())
}
}
Taken from this repo of mine: https://github.com/goktugyil/EZSwiftExtensions/commit/609fce34a41f98733f97dfd7b4c23b5d16416206
In Swift3 XCode 8 Final
Notice that the CharacterSet.whitespaces
is not a function anymore!
(Neither is NSCharacterSet.whitespaces
)
extension String {
func trim() -> String {
return self.trimmingCharacters(in: CharacterSet.whitespaces)
}
}
Another similar way:
extension String {
var trimmed:String {
return self.trimmingCharacters(in: CharacterSet.whitespaces)
}
}
Use:
let trimmedString = "myString ".trimmed
You can use the trim() method in a Swift String extension I wrote https://bit.ly/JString.
var string = "hello "
var trimmed = string.trim()
println(trimmed)// "hello"
You can also send characters that you want to be trimed
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: ","))
I created this function that allows to enter a string and returns a list of string trimmed by any character
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
}
as didn't found a way to do this in swift (compiles and work perfectly in swift 2.0)
Don't forget to import Foundation
or UIKit
.
import Foundation
let trimmedString = " aaa "".trimmingCharacters(in: .whitespaces)
print(trimmedString)
Result:
"aaa"
Otherwise you'll get:
error: value of type 'String' has no member 'trimmingCharacters'
return self.trimmingCharacters(in: .whitespaces)
**Swift 5**
extension String {
func trimAllSpace() -> String {
return components(separatedBy: .whitespacesAndNewlines).joined()
}
func trimSpace() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
**Use:**
let result = " abc ".trimAllSpace()
// result == "abc"
let ex = " abc cd ".trimSpace()
// ex == "abc cd"