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

下面是完整的例子:

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

当前回答

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

let str = "abc"
str.popLast()

// Prints ab

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

// Print <emptystring>

其他回答

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

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

使用函数advance(startIndex, endIndex):

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

Swift 3:当你想删除尾随字符串:

func replaceSuffix(_ suffix: String, replacement: String) -> String {
    if hasSuffix(suffix) {
        let sufsize = suffix.count < count ? -suffix.count : 0
        let toIndex = index(endIndex, offsetBy: sufsize)
        return substring(to: toIndex) + replacement
    }
    else
    {
        return self
    }
}

补充上述代码,我想删除字符串的开头,但在任何地方都找不到引用。以下是我的做法:

var mac = peripheral.identifier.description
let range = mac.startIndex..<mac.endIndex.advancedBy(-50)
mac.removeRange(range)  // trim 17 characters from the beginning
let txPower = peripheral.advertisements.txPower?.description

这将从字符串的开头修剪17个字符(字符串的总长度是67,从末尾向前移动-50,就得到了它。

简单回答(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答案的半衰期变得危险地短暂。学习语言并参考真正的文档总是最好的。