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

下面是完整的例子:

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

当前回答

使用函数advance(startIndex, endIndex):

var str = "45+22"
str = str.substringToIndex(advance(str.startIndex, countElements(str) - 1))

其他回答

我更喜欢下面的实现,因为我不必担心,即使字符串是空的

let str = "abc"
str.popLast()

// Prints ab

str = ""
str.popLast() // It returns the Character? which is an optional

// Print <emptystring>

斯威夫特4:

let choppedString = String(theString.dropLast())

在Swift 2中,这样做:

let choppedString = String(theString.characters.dropLast())

我推荐这个链接来了解Swift字符串。

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

一个快速变化的类别:

extension String {
    mutating func removeCharsFromEnd(removeCount:Int)
    {
        let stringLength = count(self)
        let substringIndex = max(0, stringLength - removeCount)
        self = self.substringToIndex(advance(self.startIndex, substringIndex))
    }
}

使用:

var myString = "abcd"
myString.removeCharsFromEnd(2)
println(myString) // "ab"
var str = "Hello, playground"

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

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