Remove Last Two Characters in a String (Swift 3.0)

2019-01-21 21:47发布

Is there a quick way to remove the last two characters in a String in Swift 3.0? 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!

5条回答
聊天终结者
2楼-- · 2019-01-21 22:11

update: Xcode 9 • Swift 4 or later

Now String conforms to RangeReplaceableCollection so now you can use Array's 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"

Swift 3.x

You can use the method dropLast(n:) on the characters to remove any number of characters:

let str = "0123456789"
let result = String(str.characters.dropLast(2))   // "01234567"

As an extension:

extension String {
    func dropLast(_ n: Int = 1) -> String {
        return String(characters.dropLast(n))
    }
    var dropLast: String {
        return dropLast()
    }
}

let str = "0123456789"

let result = str.dropLast(2)     // "01234567"
let result2 = result.dropLast    // "0123456"
查看更多
戒情不戒烟
3楼-- · 2019-01-21 22:17

Better to use removeLast()

var myString = "Hello world"
myString.removeLast(2)

output : "Hello wor"
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-21 22:24
var name: String = "Dolphin"
let endIndex = name.index(name.endIndex, offsetBy: -2)
let truncated = name.substring(to: endIndex)
print(name)      // "Dolphin"
print(truncated) // "Dolph"
查看更多
Deceive 欺骗
5楼-- · 2019-01-21 22:25

Use removeSubrange(Range<String.Index>) just like:

var str = "Hello, playground"
str.removeSubrange(Range(uncheckedBounds: (lower: str.index(str.endIndex, offsetBy: -2), upper: str.endIndex)))

This will crash if the string is less than 2 characters long. Is that a requirement for you?

查看更多
Fickle 薄情
6楼-- · 2019-01-21 22:33

swift 4:

let str = "Hello, playground"
let newSTR1 = str.dropLast(3)
print(newSTR1) 

output: "Hello, playgro"

//---------------//

let str = "Hello, playground"
let newSTR2 = str.dropFirst(2)
print(newSTR2)

output: "llo, playground"
查看更多
登录 后发表回答