我如何从字符串变量使用Swift删除最后一个字符?在文档中找不到。
下面是完整的例子:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
我如何从字符串变量使用Swift删除最后一个字符?在文档中找不到。
下面是完整的例子:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
当前回答
我建议使用NSString来处理你想要操作的字符串。实际上,作为一个开发人员,我从来没有遇到过NSString的问题,Swift String可以解决…我明白其中的微妙之处。但我还没有真正需要它们。
var foo = someSwiftString as NSString
or
var foo = "Foo" as NSString
or
var foo: NSString = "blah"
然后整个简单NSString字符串操作的世界就向你敞开了。
作为问题的答案
// check bounds before you do this, e.g. foo.length > 0
// Note shortFoo is of type NSString
var shortFoo = foo.substringToIndex(foo.length-1)
其他回答
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
使用新的Substring类型用法:
斯威夫特4:
var before: String = "Hello world!"
var lastCharIndex: Int = before.endIndex
var after:String = String(before[..<lastCharIndex])
print(after) // Hello world
短:
var before: String = "Hello world!"
after = String(before[..<before.endIndex])
print(after) // Hello world
一个快速变化的类别:
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"
简单回答(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答案的半衰期变得危险地短暂。学习语言并参考真正的文档总是最好的。
斯威夫特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
}