[string] Does swift have a trim method on String?

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

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

This question is related to string swift trim

The answer is


Another similar way:

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

Use:

let trimmedString = "myString ".trimmed

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"

Swift 3

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

//Swift 4.0 Remove spaces and new lines

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

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)

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

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)


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


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"

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

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 5 & 4.2

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

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

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

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to trim

How to remove whitespace from a string in typescript? Strip / trim all strings of a dataframe Best way to verify string is empty or null Does swift have a trim method on String? Trim specific character from a string Trim whitespace from a String Remove last specific character in a string c# How to delete specific characters from a string in Ruby? How to Remove the last char of String in C#? How to use a TRIM function in SQL Server