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

下面是完整的例子:

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

当前回答

斯威夫特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

}

其他回答

函数的作用是:删除字符串的最后一个元素。

var expression = "45+22"
expression = expression.dropLast()

使用函数removeAtIndex(i: String.Index)

var s = "abc"    
s.removeAtIndex(s.endIndex.predecessor())  // "ab"

斯威夫特4/5

var str = "bla"
str.removeLast() // returns "a"; str is now "bl"

我建议使用NSString来处理你想要操作的字符串。实际上,作为一个开发人员,我从来没有遇到过NSString的问题,Swift String可以解决…我明白其中的微妙之处。但我还没有真正需要它们。

var foo = someSwiftString as NSString

or

var foo = "Foo" as NSString

or

var foo: NSString = "blah"

然后整个简单NSString字符串操作的世界就向你敞开了。

作为问题的答案

// check bounds before you do this, e.g. foo.length > 0
// Note shortFoo is of type NSString
var shortFoo = foo.substringToIndex(foo.length-1)
var str = "Hello, playground"

extension String {
    var stringByDeletingLastCharacter: String {
        return dropLast(self)
    }
}

println(str.stringByDeletingLastCharacter)   // "Hello, playgroun"