294

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)
Konstantin Cherkasov
  • 3,243
  • 2
  • 18
  • 22

23 Answers23

643

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"
Craig Otis
  • 31,257
  • 32
  • 136
  • 234
  • On Xcode 6 beta 6 :'String' doesn't have a member named `substringToIndex` – ielyamani Jul 24 '14 at 22:43
  • @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? – Craig Otis Jul 24 '14 at 23:20
  • 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 – ielyamani Jul 25 '14 at 00:34
  • @Carpsen90 Can you maybe ask as a separate question? – Craig Otis Jul 25 '14 at 12:08
  • 2
    Hey, heads up, make sure it's `substringToIndex` not `substringFromIndex`. It doesn't make you feel intelligent mistaking this, let me tell you. – Louie Bertoncin Feb 01 '15 at 01:44
  • I just renamed `countElements` to `count` in the Beta4+ way part of the answer. (Swift1.2) – nacho4d Apr 21 '15 at 02:40
  • 2
    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` – kakubei Jul 22 '15 at 15:18
  • looks like advance doesn't work anymore either in Xcode 7 beta 6, do you know of a work around? – Dan Beaulieu Sep 08 '15 at 19:10
  • 2
    Swift 3: `var truncated = name.substring(to: name.index(before: name.endIndex))` – Zmey Jul 15 '16 at 21:19
  • Swift 3 in place: `name.remove(at: name.index(before: name.endIndex))` – Rob Allen Aug 01 '16 at 12:55
  • 3
    Your answer is the history of Swift evolution. – DawnSong Oct 10 '16 at 11:48
  • 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. – commscheck Oct 06 '17 at 02:26
  • 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. – Johnny Feb 03 '18 at 07:27
  • var truncated = name.substring(to: name.index(before: name.endIndex)) This worked for me in Swift 3 Thanks @CraigOtis – Dilip Tiwari Jun 19 '18 at 07:15
90

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())
Vitalii
  • 4,267
  • 1
  • 40
  • 45
gui_dos
  • 1,201
  • 8
  • 7
  • 3
    In Swift 2.0 the `characters` property on a String outputs a sequence, therefore now you have to use: `expression = expression.characters.dropLast()` – gui_dos Sep 15 '15 at 19:47
  • 5
    In Swift 2.0 for have to properly cast the result `expression = String(expression.characters.dropLast())` if you want it back as a String – cromanelli Sep 18 '15 at 18:57
74

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.

Carien van Zyl
  • 2,853
  • 22
  • 30
jrc
  • 20,354
  • 10
  • 69
  • 64
30

Swift 4/5

var str = "bla"
str.removeLast() // returns "a"; str is now "bl"
Community
  • 1
  • 1
idrougge
  • 633
  • 5
  • 12
8

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

Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
6

Use the function removeAtIndex(i: String.Index) -> Character:

var s = "abc"    
s.removeAtIndex(s.endIndex.predecessor())  // "ab"
Pang
  • 9,564
  • 146
  • 81
  • 122
Anton Serkov
  • 101
  • 1
  • 4
6

Swift 4

var welcome = "Hello World!"
welcome = String(welcome[..<welcome.index(before:welcome.endIndex)])

or

welcome.remove(at: welcome.index(before: welcome.endIndex))

or

welcome = String(welcome.dropLast())
Carien van Zyl
  • 2,853
  • 22
  • 30
5

The easiest way to trim the last character of the string is:

title = title[title.startIndex ..< title.endIndex.advancedBy(-1)]
Kunal
  • 227
  • 3
  • 9
4
import UIKit

var str1 = "Hello, playground"
str1.removeLast()
print(str1)

var str2 = "Hello, playground"
str2.removeLast(3)
print(str2)

var str3 = "Hello, playground"
str3.removeFirst(2)
print(str3)

Output:-
Hello, playgroun
Hello, playgro
llo, playground
Deepak Tagadiya
  • 2,187
  • 15
  • 28
2
let str = "abc"
let substr = str.substringToIndex(str.endIndex.predecessor())  // "ab"
Channing
  • 21
  • 1
  • 3
2
var str = "Hello, playground"

extension String {
    var stringByDeletingLastCharacter: String {
        return dropLast(self)
    }
}

println(str.stringByDeletingLastCharacter)   // "Hello, playgroun"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • kkkk I didn't even remember of this one (Swift 1.2 above). for Swift 3 version http://stackoverflow.com/a/40028338/2303865 – Leo Dabus Feb 02 '17 at 01:49
2

Short answer (valid as of 2015-04-16): removeAtIndex(myString.endIndex.predecessor())

Example:

var howToBeHappy = "Practice compassion, attention and gratitude. And smile!!"
howToBeHappy.removeAtIndex(howToBeHappy.endIndex.predecessor())
println(howToBeHappy)
// "Practice compassion, attention and gratitude. And smile!"

Meta:

The language continues its rapid evolution, making the half-life for many formerly-good S.O. answers dangerously brief. It's always best to learn the language and refer to real documentation.

Jagat Dave
  • 1,643
  • 3
  • 23
  • 30
cweekly
  • 8,706
  • 1
  • 22
  • 17
2

With the new Substring type usage:

Swift 4:

var before: String = "Hello world!"
var lastCharIndex: Int = before.endIndex
var after:String = String(before[..<lastCharIndex])
print(after) // Hello world

Shorter way:

var before: String = "Hello world!"
after = String(before[..<before.endIndex])
print(after) // Hello world
Jorge Ramírez
  • 657
  • 1
  • 7
  • 8
1

Use the function advance(startIndex, endIndex):

var str = "45+22"
str = str.substringToIndex(advance(str.startIndex, countElements(str) - 1))
Pang
  • 9,564
  • 146
  • 81
  • 122
Chen Rui
  • 385
  • 2
  • 5
1

A swift category that's mutating:

extension String {
    mutating func removeCharsFromEnd(removeCount:Int)
    {
        let stringLength = count(self)
        let substringIndex = max(0, stringLength - removeCount)
        self = self.substringToIndex(advance(self.startIndex, substringIndex))
    }
}

Use:

var myString = "abcd"
myString.removeCharsFromEnd(2)
println(myString) // "ab"
Sunkas
  • 9,542
  • 6
  • 62
  • 102
1

Another way If you want to remove one or more than one character from the end.

var myStr = "Hello World!"
myStr = (myStr as NSString).substringToIndex((myStr as NSString).length-XX)

Where XX is the number of characters you want to remove.

Kaiusee
  • 1,253
  • 1
  • 14
  • 28
1

Swift 3 (according to the docs) 20th Nov 2016

let range = expression.index(expression.endIndex, offsetBy: -numberOfCharactersToRemove)..<expression.endIndex
expression.removeSubrange(range)
narco
  • 830
  • 8
  • 21
1

The dropLast() function removes the last element of the string.

var expression = "45+22"
expression = expression.dropLast()
1

Swift 4.2

I also delete my last character from String (i.e. UILabel text) in IOS app

@IBOutlet weak var labelText: UILabel! // Do Connection with UILabel

@IBAction func whenXButtonPress(_ sender: UIButton) { // Do Connection With X Button

    labelText.text = String((labelText.text?.dropLast())!) // Delete the last caracter and assign it

}

IOS APP StoryBoard

Ashfaqur_Rahman
  • 140
  • 1
  • 9
0

I'd recommend using NSString for strings that you want to manipulate. Actually come to think of it as a developer I've never run into a problem with NSString that Swift String would solve... I understand the subtleties. But I've yet to have an actual need for them.

var foo = someSwiftString as NSString

or

var foo = "Foo" as NSString

or

var foo: NSString = "blah"

And then the whole world of simple NSString string operations is open to you.

As answer to the question

// check bounds before you do this, e.g. foo.length > 0
// Note shortFoo is of type NSString
var shortFoo = foo.substringToIndex(foo.length-1)
n13
  • 6,843
  • 53
  • 40
0

complimentary to the above code I wanted to remove the beginning of the string and could not find a reference anywhere. Here is how I did it:

var mac = peripheral.identifier.description
let range = mac.startIndex..<mac.endIndex.advancedBy(-50)
mac.removeRange(range)  // trim 17 characters from the beginning
let txPower = peripheral.advertisements.txPower?.description

This trims 17 characters from the beginning of the string (he total string length is 67 we advance -50 from the end and there you have it.

pkamb
  • 33,281
  • 23
  • 160
  • 191
Sophman
  • 85
  • 2
  • 17
0

Swift 3: When you want to remove trailing string:

func replaceSuffix(_ suffix: String, replacement: String) -> String {
    if hasSuffix(suffix) {
        let sufsize = suffix.count < count ? -suffix.count : 0
        let toIndex = index(endIndex, offsetBy: sufsize)
        return substring(to: toIndex) + replacement
    }
    else
    {
        return self
    }
}
slashlos
  • 913
  • 9
  • 17
0

I prefer the below implementation because I don't have to worry even if the string is empty

let str = "abc"
str.popLast()

// Prints ab

str = ""
str.popLast() // It returns the Character? which is an optional

// Print <emptystring>
Nalam
  • 314
  • 3
  • 8