一尘不染

从字符串中删除最后一个字符。斯威夫特语言

swift

如何使用Swift从String变量中删除最后一个字符?在文档中找不到它。

这是完整的示例:

var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)

阅读 226

收藏
2020-07-07

共1个答案

一尘不染

Swift 4.0(也是Swift 5.0)

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)

斯威夫特3.0

这些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!

Swift 2.0+方式

有几种方法可以实现此目的:

通过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"

旧的String.Index(Xcode 6 Beta 4 +)方式

由于StringSwift中的类型旨在提供出色的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"

注意:
我发现这是理解的一个很好的起点String.Index

旧版(测试版4之前)

您可以简单地使用该substringToIndex()函数,为其提供的长度要小于String

let name: String = "Dolphin"
name.substringToIndex(countElements(name) - 1) // "Dolphi"
2020-07-07