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

下面是完整的例子:

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

当前回答

一个快速变化的类别:

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"

其他回答

一个快速变化的类别:

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"

使用新的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

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

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

修剪字符串最后一个字符最简单的方法是:

title = title[title.startIndex ..< title.endIndex.advancedBy(-1)]

斯威夫特4:

let choppedString = String(theString.dropLast())

在Swift 2中,这样做:

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

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