Remove last character from string. Swift language
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
Related videos on Youtube
Konstantin Cherkasov
Updated on July 21, 2022Comments
-
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)
-
Fattie over 7 years2017, MODERN ANSWER: stackoverflow.com/a/39610807/294884
-
-
ielyamani almost 10 yearsOn Xcode 6 beta 6 :'String' doesn't have a member named
substringToIndex
-
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 asubstringToIndex()
method. Can you clarify? -
ielyamani almost 10 yearsI 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 almost 10 years@Carpsen90 Can you maybe ask as a separate question?
-
ZYiOS over 9 yearsHi, have you test emojis?
-
Maxim Shoustin over 9 years@ZuYuan what is emojis?
-
Louie Bertoncin over 9 yearsHey, heads up, make sure it's
substringToIndex
notsubstringFromIndex
. It doesn't make you feel intelligent mistaking this, let me tell you. -
nacho4d about 9 yearsI just renamed
countElements
tocount
in the Beta4+ way part of the answer. (Swift1.2) -
kakubei almost 9 yearsThis 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 over 8 yearslooks like advance doesn't work anymore either in Xcode 7 beta 6, do you know of a work around?
-
gui_dos over 8 yearsIn Swift 2.0 the
characters
property on a String outputs a sequence, therefore now you have to use:expression = expression.characters.dropLast()
-
cromanelli over 8 yearsIn Swift 2.0 for have to properly cast the result
expression = String(expression.characters.dropLast())
if you want it back as a String -
Zmey almost 8 yearsSwift 3:
var truncated = name.substring(to: name.index(before: name.endIndex))
-
Rob Allen almost 8 yearsSwift 3 in place:
name.remove(at: name.index(before: name.endIndex))
-
Letaief Achraf over 7 yearsThank you, a very elegant way to remove as many characters as you want from the end of a string.
-
DawnSong over 7 yearsYour answer is the history of Swift evolution.
-
Leo Dabus over 7 yearskkkk I didn't even remember of this one (Swift 1.2 above). for Swift 3 version stackoverflow.com/a/40028338/2303865
-
commscheck over 6 yearsNote 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 over 6 yearsThat'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 returnsVoid
, and it did well. -
Dilip Tiwari almost 6 yearsvar truncated = name.substring(to: name.index(before: name.endIndex)) This worked for me in Swift 3 Thanks @CraigOtis
-
Starsky over 3 yearsCould be just
let choppedString = theString.dropLast().description
.