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

下面是完整的例子:

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

当前回答

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

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

其他回答

斯威夫特4/5

var str = "bla"
str.removeLast() // returns "a"; str is now "bl"
let str = "abc"
let substr = str.substringToIndex(str.endIndex.predecessor())  // "ab"
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

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

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

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