Remove Last Two Characters in a String

前端 未结 5 810
旧巷少年郎
旧巷少年郎 2020-12-13 03:15

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 ho

相关标签:
5条回答
  • 2020-12-13 03:59

    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
    
    0 讨论(0)
  • 2020-12-13 04:09

    Better to use removeLast()

    var myString = "Hello world"
    myString.removeLast(2)
    
    output : "Hello wor"
    
    0 讨论(0)
  • 2020-12-13 04:10

    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?

    0 讨论(0)
  • 2020-12-13 04:11
    var name: String = "Dolphin"
    let endIndex = name.index(name.endIndex, offsetBy: -2)
    let truncated = name.substring(to: endIndex)
    print(name)      // "Dolphin"
    print(truncated) // "Dolph"
    
    0 讨论(0)
  • 2020-12-13 04:19

    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"
    
    0 讨论(0)
提交回复
热议问题