Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Last Two Characters in a String

Is there a quick way to remove the last two characters in a String in Swift? I see there is a simple way to remove the last character as clearly noted here. Do you know how to remove the last two characters? Thanks!

like image 247
Ben Avatar asked Oct 13 '16 18:10

Ben


People also ask

How do I remove the last two characters of a string?

Use the String. substring() method to remove the last 2 characters from a string, e.g. const removedLast2 = str. substring(0, str. length - 2); .

How do I remove the last 3 characters of a string?

slice() method to remove the last 3 characters from a string, e.g. const withoutLast3 = str. slice(0, -3); . The slice method will return a new string that doesn't contain the last 3 characters of the original string.


2 Answers

update: Xcode 9 • Swift 4 or later

String now conforms to RangeReplaceableCollection so you can use collection method dropLast straight in the String and therefore an extension it is not necessary anymore. The only difference is that it returns a Substring. If you need a String you need to initialize a new one from it:

let string = "0123456789" let substring1 = string.dropLast(2)         // "01234567" let substring2 = substring1.dropLast()      // "0123456" let result = String(substring2.dropLast())  // "012345" 

We can also extend LosslessStringConvertible to add trailing syntax which I think improves readability:

extension LosslessStringConvertible {     var string: String { .init(self) } } 

Usage:

let result = substring.dropLast().string 
like image 170
Leo Dabus Avatar answered Sep 29 '22 00:09

Leo Dabus


var name: String = "Dolphin" let endIndex = name.index(name.endIndex, offsetBy: -2) let truncated = name.substring(to: endIndex) print(name)      // "Dolphin" print(truncated) // "Dolph" 
like image 41
Naveen Ramanathan Avatar answered Sep 28 '22 22:09

Naveen Ramanathan