Remove last character from string. Swift language

190,074

Solution 1

Swift 4.0 (also Swift 5.0)

var str = "Hello, World"                           // "Hello, World"
str.dropLast()                                     // "Hello, Worl" (non-modifying)
str                                                // "Hello, World"
String(str.dropLast())                             // "Hello, Worl"

str.remove(at: str.index(before: str.endIndex))    // "d"
str                                                // "Hello, Worl" (modifying)

Swift 3.0

The APIs have gotten a bit more swifty, and as a result the Foundation extension has changed a bit:

var name: String = "Dolphin"
var truncated = name.substring(to: name.index(before: name.endIndex))
print(name)      // "Dolphin"
print(truncated) // "Dolphi"

Or the in-place version:

var name: String = "Dolphin"
name.remove(at: name.index(before: name.endIndex))
print(name)      // "Dolphi"

Thanks Zmey, Rob Allen!

Swift 2.0+ Way

There are a few ways to accomplish this:

Via the Foundation extension, despite not being part of the Swift library:

var name: String = "Dolphin"
var truncated = name.substringToIndex(name.endIndex.predecessor())
print(name)      // "Dolphin"
print(truncated) // "Dolphi"

Using the removeRange() method (which alters the name):

var name: String = "Dolphin"    
name.removeAtIndex(name.endIndex.predecessor())
print(name) // "Dolphi"

Using the dropLast() function:

var name: String = "Dolphin"
var truncated = String(name.characters.dropLast())
print(name)      // "Dolphin"
print(truncated) // "Dolphi"

Old String.Index (Xcode 6 Beta 4 +) Way

Since String types in Swift aim to provide excellent UTF-8 support, you can no longer access character indexes/ranges/substrings using Int types. Instead, you use String.Index:

let name: String = "Dolphin"
let stringLength = count(name) // Since swift1.2 `countElements` became `count`
let substringIndex = stringLength - 1
name.substringToIndex(advance(name.startIndex, substringIndex)) // "Dolphi"

Alternatively (for a more practical, but less educational example) you can use endIndex:

let name: String = "Dolphin"
name.substringToIndex(name.endIndex.predecessor()) // "Dolphi"

Note: I found this to be a great starting point for understanding String.Index

Old (pre-Beta 4) Way

You can simply use the substringToIndex() function, providing it one less than the length of the String:

let name: String = "Dolphin"
name.substringToIndex(countElements(name) - 1) // "Dolphi"

Solution 2

The global dropLast() function works on sequences and therefore on Strings:

var expression  = "45+22"
expression = dropLast(expression)  // "45+2"

// in Swift 2.0 (according to cromanelli's comment below)
expression = String(expression.characters.dropLast())

Solution 3

Swift 4:

let choppedString = String(theString.dropLast())

In Swift 2, do this:

let choppedString = String(theString.characters.dropLast())

I recommend this link to get an understanding of Swift strings.

Solution 4

Swift 4/5

var str = "bla"
str.removeLast() // returns "a"; str is now "bl"

Solution 5

This is a String Extension Form:

extension String {

    func removeCharsFromEnd(count_:Int) -> String {
        let stringLength = count(self)

        let substringIndex = (stringLength < count_) ? 0 : stringLength - count_

        return self.substringToIndex(advance(self.startIndex, substringIndex))
    }
}

for versions of Swift earlier than 1.2:

...
let stringLength = countElements(self)
...

Usage:

var str_1 = "Maxim"
println("output: \(str_1.removeCharsFromEnd(1))") // "Maxi"
println("output: \(str_1.removeCharsFromEnd(3))") // "Ma"
println("output: \(str_1.removeCharsFromEnd(8))") // ""

Reference:

Extensions add new functionality to an existing class, structure, or enumeration type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling). Extensions are similar to categories in Objective-C. (Unlike Objective-C categories, Swift extensions do not have names.)

See DOCS

Share:
190,074

Related videos on Youtube

Konstantin Cherkasov
Author by

Konstantin Cherkasov

Updated on July 21, 2022

Comments

  • Konstantin Cherkasov
    Konstantin Cherkasov almost 2 years

    How can I remove last character from String variable using Swift? Can't find it in documentation.

    Here is full example:

    var expression = "45+22"
    expression = expression.substringToIndex(countElements(expression) - 1)
    
  • ielyamani
    ielyamani almost 10 years
    On Xcode 6 beta 6 :'String' doesn't have a member named substringToIndex
  • Craig Otis
    Craig Otis almost 10 years
    @Carpsen90 There is no beta 6. (As of this writing.) And in the most recent beta (beta 4), the String type definitely has a substringToIndex() method. Can you clarify?
  • ielyamani
    ielyamani almost 10 years
    I am sorry I meant beta 4.. and it is definitely not working for me.. I had to cast the string to NSString to have access to more functions
  • Craig Otis
    Craig Otis almost 10 years
    @Carpsen90 Can you maybe ask as a separate question?
  • ZYiOS
    ZYiOS over 9 years
    Hi, have you test emojis?
  • Maxim Shoustin
    Maxim Shoustin over 9 years
    @ZuYuan what is emojis?
  • Louie Bertoncin
    Louie Bertoncin over 9 years
    Hey, heads up, make sure it's substringToIndex not substringFromIndex. It doesn't make you feel intelligent mistaking this, let me tell you.
  • nacho4d
    nacho4d about 9 years
    I just renamed countElements to count in the Beta4+ way part of the answer. (Swift1.2)
  • kakubei
    kakubei almost 9 years
    This is true, as of July 21st, Xcode 7 Beta 4 says 'String' doesn't have a member named substringToIndex. Also, as of Xcode 7, string no longer has a .count property, it is now only applied to characters: string.characters.count
  • Dan Beaulieu
    Dan Beaulieu over 8 years
    looks like advance doesn't work anymore either in Xcode 7 beta 6, do you know of a work around?
  • gui_dos
    gui_dos over 8 years
    In Swift 2.0 the characters property on a String outputs a sequence, therefore now you have to use: expression = expression.characters.dropLast()
  • cromanelli
    cromanelli over 8 years
    In Swift 2.0 for have to properly cast the result expression = String(expression.characters.dropLast()) if you want it back as a String
  • Zmey
    Zmey almost 8 years
    Swift 3: var truncated = name.substring(to: name.index(before: name.endIndex))
  • Rob Allen
    Rob Allen almost 8 years
    Swift 3 in place: name.remove(at: name.index(before: name.endIndex))
  • Letaief Achraf
    Letaief Achraf over 7 years
    Thank you, a very elegant way to remove as many characters as you want from the end of a string.
  • DawnSong
    DawnSong over 7 years
    Your answer is the history of Swift evolution.
  • Leo Dabus
    Leo Dabus over 7 years
    kkkk I didn't even remember of this one (Swift 1.2 above). for Swift 3 version stackoverflow.com/a/40028338/2303865
  • commscheck
    commscheck over 6 years
    Note that in Swift 4 strings are back to being collections, and the .substring(to:) method is deprecated. The options listed under Swift 2.0+ worked for me in Swift 4.
  • Johnny
    Johnny over 6 years
    That's not working in Swift 4, Xcode 9. So I did this placeStr.removeLast(1) which means remove the last character from the string and returns Void, and it did well.
  • Dilip Tiwari
    Dilip Tiwari almost 6 years
    var truncated = name.substring(to: name.index(before: name.endIndex)) This worked for me in Swift 3 Thanks @CraigOtis
  • Starsky
    Starsky over 3 years
    Could be just let choppedString = theString.dropLast().description.