我如何从字符串变量使用Swift删除最后一个字符?在文档中找不到。
下面是完整的例子:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
我如何从字符串变量使用Swift删除最后一个字符?在文档中找不到。
下面是完整的例子:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
当前回答
Swift 3(根据文档)2016年11月20日
let range = expression.index(expression.endIndex, offsetBy: -numberOfCharactersToRemove)..<expression.endIndex
expression.removeSubrange(range)
其他回答
斯威夫特4
var welcome = "Hello World!"
welcome = String(welcome[..<welcome.index(before:welcome.endIndex)])
or
welcome.remove(at: welcome.index(before: welcome.endIndex))
or
welcome = String(welcome.dropLast())
全局的dropLast()函数作用于序列,因此也作用于字符串:
var expression = "45+22"
expression = dropLast(expression) // "45+2"
// in Swift 2.0 (according to cromanelli's comment below)
expression = String(expression.characters.dropLast())
修剪字符串最后一个字符最简单的方法是:
title = title[title.startIndex ..< title.endIndex.advancedBy(-1)]
let str = "abc"
let substr = str.substringToIndex(str.endIndex.predecessor()) // "ab"
斯威夫特4.2
我还删除了我的最后一个字符从字符串(即UILabel文本)在IOS应用程序
@IBOutlet weak var labelText: UILabel! // Do Connection with UILabel
@IBAction func whenXButtonPress(_ sender: UIButton) { // Do Connection With X Button
labelText.text = String((labelText.text?.dropLast())!) // Delete the last caracter and assign it
}