Does swift have a trim method on String?

StringSwiftTrim

String Problem Overview


Does swift have a trim method on String? For example:

let result = " abc ".trim()
// result == "abc"

String Solutions


Solution 1 - String

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"

Solution 2 - String

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"

Solution 3 - String

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" */

Solution 4 - String

Swift 5 & 4.2

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

Solution 5 - String

Swift 3

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

Solution 6 - String

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"

Solution 7 - String

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 

Solution 8 - String

//Swift 4.0 Remove spaces and new lines

extension String {
    func trim() -> String {
        return self.trimmingCharacters(in: .whitespacesAndNewlines)         
    }
}

Solution 9 - String

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

Solution 10 - String

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

Solution 11 - String

Another similar way:

extension String {
    var trimmed:String {
        return self.trimmingCharacters(in: CharacterSet.whitespaces)
    }
}

Use:

let trimmedString = "myString ".trimmed

Solution 12 - String

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"

Solution 13 - String

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: ","))

Solution 14 - String

**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"

Solution 15 - String

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)

Solution 16 - String

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontounaobunView Question on Stackoverflow
Solution 1 - StringSivanraj MView Answer on Stackoverflow
Solution 2 - StringThiago ArreguyView Answer on Stackoverflow
Solution 3 - StringBishow GurungView Answer on Stackoverflow
Solution 4 - StringSaranjithView Answer on Stackoverflow
Solution 5 - StringWarif Akhand RishiView Answer on Stackoverflow
Solution 6 - StringAmin AliariView Answer on Stackoverflow
Solution 7 - StringViJay AvhadView Answer on Stackoverflow
Solution 8 - StringDanielvgftvView Answer on Stackoverflow
Solution 9 - StringEsqarrouthView Answer on Stackoverflow
Solution 10 - StringMartin AlgestenView Answer on Stackoverflow
Solution 11 - StringVikerView Answer on Stackoverflow
Solution 12 - StringWilliam FalconView Answer on Stackoverflow
Solution 13 - StringVarun NahariaView Answer on Stackoverflow
Solution 14 - StringZoroView Answer on Stackoverflow
Solution 15 - StringYeis GallegosView Answer on Stackoverflow
Solution 16 - StringNonCreature0714View Answer on Stackoverflow