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

下面是完整的例子:

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

当前回答

var str = "Hello, playground"

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

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

其他回答

这是一个字符串扩展表单:

extension String {

    func removeCharsFromEnd(count_:Int) -> String {
        let stringLength = count(self)

        let substringIndex = (stringLength < count_) ? 0 : stringLength - count_

        return self.substringToIndex(advance(self.startIndex, substringIndex))
    }
}

对于Swift 1.2之前的版本:

...
let stringLength = countElements(self)
...

用法:

var str_1 = "Maxim"
println("output: \(str_1.removeCharsFromEnd(1))") // "Maxi"
println("output: \(str_1.removeCharsFromEnd(3))") // "Ma"
println("output: \(str_1.removeCharsFromEnd(8))") // ""

参考:

扩展向现有的类、结构或枚举类型添加新功能。这包括扩展您无法访问原始源代码的类型的能力(称为回溯建模)。扩展类似于Objective-C中的类别。(与Objective-C类别不同,Swift扩展没有名称。)

看文档

全局的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())

另一种方法如果你想从末尾删除一个或多个字符。

var myStr = "Hello World!"
myStr = (myStr as NSString).substringToIndex((myStr as NSString).length-XX)

其中XX是要删除的字符数。

import UIKit

var str1 = "Hello, playground"
str1.removeLast()
print(str1)

var str2 = "Hello, playground"
str2.removeLast(3)
print(str2)

var str3 = "Hello, playground"
str3.removeFirst(2)
print(str3)

Output:-
Hello, playgroun
Hello, playgro
llo, playground
let str = "abc"
let substr = str.substringToIndex(str.endIndex.predecessor())  // "ab"