如何使用Swift从字符串变量中删除最后一个字符?在文档中找不到它。
这里是完整的例子:
var expression = "45+22" expression = expression.substringToIndex(countElements(expression) - 1)
新的Swift 3.0方式
原文链接:https://www.f2er.com/swift/321764.htmlAPI已经变得更加迅速,因此Foundation扩展已经改变了一点:
var name: String = "Dolphin" var truncated = name.substring(to: name.index(before: name.endIndex)) print(name) // "Dolphin" print(truncated) // "Dolphi"
或者就地版本:
var name: String = "Dolphin" name.remove(at: name.index(before: name.endIndex)) print(name) // "Dolphi"
谢谢Zmey,Rob Allen!
Swift 2.0方式
有几种方法可以实现这一点:
通过基金会扩展,尽管不是Swift库的一部分:
var name: String = "Dolphin" var truncated = name.substringToIndex(name.endIndex.predecessor()) print(name) // "Dolphin" print(truncated) // "Dolphi"
var name: String = "Dolphin" name.removeAtIndex(name.endIndex.predecessor()) print(name) // "Dolphi"
使用dropLast()函数:
var name: String = "Dolphin" var truncated = String(name.characters.dropLast()) print(name) // "Dolphin" print(truncated) // "Dolphi"
Old String.Index(Xcode 6 Beta 4)方式
由于Swift中的String类型旨在提供出色的UTF-8支持,因此您不能再使用Int类型访问字符索引/范围/子字符串。相反,你使用String.Index:
let name: String = "Dolphin" let stringLength = count(name) // Since swift1.2 `countElements` became `count` let substringIndex = stringLength - 1 name.substringToIndex(advance(name.startIndex,substringIndex)) // "Dolphi"
或者(对于更实用,但较少教育的例子),你可以使用endIndex:
let name: String = "Dolphin" name.substringToIndex(name.endIndex.predecessor()) // "Dolphi"
注意:我发现this是理解String.Index的一个很好的起点
老(pre-beta 4)方式
你可以简单地使用substringToIndex()函数,提供一个小于字符串的长度:
let name: String = "Dolphin" name.substringToIndex(countElements(name) - 1) // "Dolphi"