我如何从字符串变量使用Swift删除最后一个字符?在文档中找不到。
下面是完整的例子:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
我如何从字符串变量使用Swift删除最后一个字符?在文档中找不到。
下面是完整的例子:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
当前回答
简单回答(2015-04-16有效):removeAtIndex(mystring . endindex .前任())
例子:
var howToBeHappy = "Practice compassion, attention and gratitude. And smile!!"
howToBeHappy.removeAtIndex(howToBeHappy.endIndex.predecessor())
println(howToBeHappy)
// "Practice compassion, attention and gratitude. And smile!"
元:
语言继续着它的快速进化,使得许多以前很好的sos答案的半衰期变得危险地短暂。学习语言并参考真正的文档总是最好的。
其他回答
另一种方法如果你想从末尾删除一个或多个字符。
var myStr = "Hello World!"
myStr = (myStr as NSString).substringToIndex((myStr as NSString).length-XX)
其中XX是要删除的字符数。
使用新的Substring类型用法:
斯威夫特4:
var before: String = "Hello world!"
var lastCharIndex: Int = before.endIndex
var after:String = String(before[..<lastCharIndex])
print(after) // Hello world
短:
var before: String = "Hello world!"
after = String(before[..<before.endIndex])
print(after) // Hello world
斯威夫特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
}
使用函数removeAtIndex(i: String.Index)
var s = "abc"
s.removeAtIndex(s.endIndex.predecessor()) // "ab"
全局的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())