我如何从字符串变量使用Swift删除最后一个字符?在文档中找不到。
下面是完整的例子:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
我如何从字符串变量使用Swift删除最后一个字符?在文档中找不到。
下面是完整的例子:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 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
}
}
其他回答
修剪字符串最后一个字符最简单的方法是:
title = title[title.startIndex ..< title.endIndex.advancedBy(-1)]
简单回答(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答案的半衰期变得危险地短暂。学习语言并参考真正的文档总是最好的。
使用函数removeAtIndex(i: String.Index)
var s = "abc"
s.removeAtIndex(s.endIndex.predecessor()) // "ab"
Swift 3(根据文档)2016年11月20日
let range = expression.index(expression.endIndex, offsetBy: -numberOfCharactersToRemove)..<expression.endIndex
expression.removeSubrange(range)
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
}
}