我如何从字符串变量使用Swift删除最后一个字符?在文档中找不到。
下面是完整的例子:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
我如何从字符串变量使用Swift删除最后一个字符?在文档中找不到。
下面是完整的例子:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
当前回答
斯威夫特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())
其他回答
let str = "abc"
let substr = str.substringToIndex(str.endIndex.predecessor()) // "ab"
修剪字符串最后一个字符最简单的方法是:
title = title[title.startIndex ..< title.endIndex.advancedBy(-1)]
斯威夫特4/5
var str = "bla"
str.removeLast() // returns "a"; str is now "bl"
补充上述代码,我想删除字符串的开头,但在任何地方都找不到引用。以下是我的做法:
var mac = peripheral.identifier.description
let range = mac.startIndex..<mac.endIndex.advancedBy(-50)
mac.removeRange(range) // trim 17 characters from the beginning
let txPower = peripheral.advertisements.txPower?.description
这将从字符串的开头修剪17个字符(字符串的总长度是67,从末尾向前移动-50,就得到了它。
斯威夫特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
}