424

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

let result = " abc ".trim()
// result == "abc"
budiDino
  • 13,044
  • 8
  • 95
  • 91
tounaobun
  • 14,570
  • 9
  • 53
  • 75

16 Answers16

864

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"
Lioness100
  • 8,260
  • 6
  • 18
  • 49
Sivanraj M
  • 8,867
  • 1
  • 14
  • 9
  • Will not work on swif 1.2, as there is no automatic convention from String into NSString. – elcuco Jun 18 '15 at 07:07
  • 5
    It works fine in Swift 1.2 - the String object has stringByTrimmingCharactersInSet method (it isn't an NSString exclusive) – Ben Dodson Jul 10 '15 at 11:19
  • Swift3 has removed that (and does not offer an alternative) >:-( – qwerty_so Sep 14 '16 at 13:12
  • 9
    In Swift 3.0 is: let trimmedString = myString.trimmingCharacters(in: .whitespaces) – kikettas Sep 19 '16 at 23:38
  • 6
    That doesn't mean it is outdated. Not everyone is using Swift 3.0 yet. – c.dunlap Sep 30 '16 at 14:44
  • 2
    In Swift 3.0 this will not remove white spaces in between string. It'll only remove leading and trailing white spaces. For that refer this answer: http://stackoverflow.com/a/39067610/4886069 –  Oct 07 '16 at 10:43
  • Swift 4 : `.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines );` – Top-Master May 22 '21 at 15:40
142

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"
Soumen
  • 2,070
  • 21
  • 25
Thiago Arreguy
  • 2,739
  • 2
  • 19
  • 18
  • 2
    Is that safe? How do I prevent a method name collision if Apple or some third party library adds the same method to `String`? – ma11hew28 Nov 20 '15 at 14:39
  • 12
    Extensions are safe - and in fact Apple makes prolific use of them in their internal APIs. You cannot prevent any name collisions, and this is in fact good. You will get a compile error when Apple does finally add a trim() method and you will know that your extension is no longer required. Extensions are quite elegant and put methods where you need them rather than some obscure utility class like StringUtils - the problem I have is when a class doesn't have a method I need because some other framework wasn't imported that added extensions to it. – absmiths Dec 15 '15 at 15:09
  • 3
    Hey, in Swift 3 should be return `return self.trimmingCharacters(in: .whitespacesAndNewlines)` –  Nov 04 '16 at 14:59
  • 7
    let result = " Hello World ".trim() // result = "HelloWorld" this will not remove the whitespaces contained in string. will remve only leading and trailing spaces. – Sahil Jul 14 '17 at 10:26
  • 3
    this will not remove spaces in between string. It only removes leading and trailing space. So better way to remove spaces in between string is use yourtext?.replacingOccurrences(of: " ", with: "") instead of using trimmingCharacters – Umesh Sawant Aug 04 '17 at 06:38
  • 2
    Example, " Hello World " -> "HelloWorld" is very misleading as trimmingCharacters method does not remove the space between "Hello" and "World" – markckim Jan 20 '19 at 04:25
62

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" */
Aditya Srivastava
  • 2,630
  • 2
  • 13
  • 23
Bishow Gurung
  • 1,962
  • 12
  • 15
  • 4
    What if I only want to trim trailing and leading whitespace? – Suragch Aug 16 '16 at 16:34
  • 1
    I'm new to swift 3 extensions. If a library modifies String, and I also modify String, is it possible to get collisions? What if future versions of swift ad a trim() method? So.. basically.. are extensions safe to use like this? – Gattster Oct 14 '16 at 22:46
  • 1
    it's possible to get collisions. – Alex Brown Mar 29 '17 at 06:16
  • 1
    let result = " Hello World ".trim() // result = "HelloWorld" this will not remove the whitespaces contained in string. will remve only leading and trailing spaces – Sahil Jul 14 '17 at 10:26
54

Swift 5 & 4.2

let trimmedString = " abc ".trimmingCharacters(in: .whitespaces)
 //trimmedString == "abc"
Saranjith
  • 11,242
  • 5
  • 69
  • 122
21

Swift 3

let result = " abc ".trimmingCharacters(in: .whitespacesAndNewlines)
Warif Akhand Rishi
  • 23,920
  • 8
  • 80
  • 107
12

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"
Amin
  • 543
  • 7
  • 12
5

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 
Alex Brown
  • 41,819
  • 10
  • 94
  • 108
ViJay Avhad
  • 2,684
  • 22
  • 26
5

//Swift 4.0 Remove spaces and new lines

extension String {
    func trim() -> String {
        return self.trimmingCharacters(in: .whitespacesAndNewlines)         
    }
}
badhanganesh
  • 3,427
  • 3
  • 18
  • 39
Danielvgftv
  • 547
  • 7
  • 6
4
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

Esqarrouth
  • 38,543
  • 21
  • 161
  • 168
4

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)
    }
}
Martin Algesten
  • 13,052
  • 4
  • 54
  • 77
4

Another similar way:

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

Use:

let trimmedString = "myString ".trimmed
Viker
  • 3,183
  • 2
  • 25
  • 25
3

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"
William Falcon
  • 9,813
  • 14
  • 67
  • 110
2

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: ","))
Varun Naharia
  • 5,318
  • 10
  • 50
  • 84
0

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)

Yeis Gallegos
  • 444
  • 2
  • 14
  • 2
    can you define what you mean by 'trim', with an example. Since your return type is [String] you cannot be implementing what the OP requested. (which returns a String) – Alex Brown Mar 29 '17 at 06:14
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)
NonCreature0714
  • 5,744
  • 10
  • 30
  • 52
0
**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"
Zoro
  • 19
  • 4