我如何从字符串变量使用Swift删除最后一个字符?在文档中找不到。
下面是完整的例子:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
我如何从字符串变量使用Swift删除最后一个字符?在文档中找不到。
下面是完整的例子:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
当前回答
斯威夫特4.2
我还删除了我的最后一个字符从字符串(即UILabel文本)在IOS应用程序
@IBOutlet weak var labelText: UILabel! // Do Connection with UILabel
@IBAction func whenXButtonPress(_ sender: UIButton) { // Do Connection With X Button
labelText.text = String((labelText.text?.dropLast())!) // Delete the last caracter and assign it
}
其他回答
使用函数removeAtIndex(i: String.Index)
var s = "abc"
s.removeAtIndex(s.endIndex.predecessor()) // "ab"
斯威夫特4.2
我还删除了我的最后一个字符从字符串(即UILabel文本)在IOS应用程序
@IBOutlet weak var labelText: UILabel! // Do Connection with UILabel
@IBAction func whenXButtonPress(_ sender: UIButton) { // Do Connection With X Button
labelText.text = String((labelText.text?.dropLast())!) // Delete the last caracter and assign it
}
这是一个字符串扩展表单:
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扩展没有名称。)
看文档
使用函数advance(startIndex, endIndex):
var str = "45+22"
str = str.substringToIndex(advance(str.startIndex, countElements(str) - 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"