var str = 'Hello, World' // 'Hello, World'str.dropLast() // 'Hello, Worl' (non-modifying)str// 'Hello, World'String(str.dropLast()) // 'Hello, Worl'str.remove(at: str.index(before: str.endindex)) // 'd'str// 'Hello, Worl' (modifying)
这些API变得更加 快捷 ,因此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!
有几种方法可以实现此目的:
通过Foundation扩展,尽管不属于Swift库:
var name: String = 'Dolphin'var truncated = name.substringToIndex(name.endindex.predecessor())print(name) // 'Dolphin'print(truncated) // 'Dolphi'
使用removeRange()方法(其 涂改 的name):
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'
由于StringSwift中的类型旨在提供出色的UTF-8支持,因此您不能再使用Int类型访问字符索引/范围/子字符串。而是使用String.Index:
let name: String = 'Dolphin'let stringLength = count(name) // Since swift1.2 `countElements` became `count`let substringIndex = stringLength - 1name.substringToIndex(advance(name.startIndex, substringIndex)) // 'Dolphi'
另外(对于一个更实际,但不太教育的示例),您可以使用endindex:
let name: String = 'Dolphin'name.substringToIndex(name.endindex.predecessor()) // 'Dolphi'
注意:我发现这是理解的一个很好的起点String.Index
您可以简单地使用该substringToIndex()函数,为其提供的长度要小于String:
let name: String = 'Dolphin'name.substringToIndex(countElements(name) - 1) // 'Dolphi'解决方法
如何使用Swift从String变量中删除最后一个字符?在文档中找不到它。
这是完整的示例:
var expression = '45+22'expression = expression.substringToIndex(countElements(expression) - 1)