Remove Last Two Characters in a String

前端 未结 5 820
旧巷少年郎
旧巷少年郎 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 04:10

    Use removeSubrange(Range) 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?

提交回复
热议问题