删除字符串中的最后两个字符 [英] Remove Last Two Characters in a String

查看:523
本文介绍了删除字符串中的最后两个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种快速的方法来删除Swift中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!

推荐答案

更新: Xcode 9•Swift 4或更高版本

String现在符合RangeReplaceableCollection,因此您可以直接在String中使用收集方法dropLast,因此不再需要扩展.唯一的区别是它返回一个Substring.如果您需要一个字符串,则需要从中初始化一个新字符串:

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"


我们还可以扩展LosslessStringConvertible以添加尾随语法,我认为这可以提高可读性:


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

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


用法:

let result = substring.dropLast().string

这篇关于删除字符串中的最后两个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆