如何使用Swift从String变量中删除最后一个字符?在文档中找不到它。
这是完整的示例:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
如何使用Swift从String变量中删除最后一个字符?在文档中找不到它。
这是完整的示例:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
Answers:
Swift 4.0(也是Swift 5.0)
var str = "Hello, World" // "Hello, World"
str.dropLast() // "Hello, Worl" (non-modifying)
str // "Hello, World"
String(str.dropLast()) // "Hello, Worl"
str.remove(at: str.index(before: str.endIndex)) // "d"
str // "Hello, Worl" (modifying)
斯威夫特3.0
这些API变得更加快捷,因此Foundation扩展有所改变:
var name: String = "Dolphin"
var truncated = name.substring(to: name.index(before: name.endIndex))
print(name) // "Dolphin"
print(truncated) // "Dolphi"
或就地版本:
var name: String = "Dolphin"
name.remove(at: name.index(before: name.endIndex))
print(name) // "Dolphi"
感谢Zmey,Rob Allen!
Swift 2.0+方式
有几种方法可以实现此目的:
通过Foundation扩展,尽管不属于Swift库:
var name: String = "Dolphin"
var truncated = name.substringToIndex(name.endIndex.predecessor())
print(name) // "Dolphin"
print(truncated) // "Dolphi"
使用removeRange()
方法(其涂改的name
):
var name: String = "Dolphin"
name.removeAtIndex(name.endIndex.predecessor())
print(name) // "Dolphi"
使用dropLast()
功能:
var name: String = "Dolphin"
var truncated = String(name.characters.dropLast())
print(name) // "Dolphin"
print(truncated) // "Dolphi"
旧的String.Index(Xcode 6 Beta 4 +)方式
由于String
Swift中的类型旨在提供出色的UTF-8支持,因此您将无法再使用Int
类型访问字符索引/范围/子字符串。而是使用String.Index
:
let name: String = "Dolphin"
let stringLength = count(name) // Since swift1.2 `countElements` became `count`
let substringIndex = stringLength - 1
name.substringToIndex(advance(name.startIndex, substringIndex)) // "Dolphi"
或者(可以使用一个更实际但又不那么受教育的示例),您可以使用endIndex
:
let name: String = "Dolphin"
name.substringToIndex(name.endIndex.predecessor()) // "Dolphi"
注意:我发现这是理解的一个很好的起点String.Index
旧版(测试版4之前)
您可以简单地使用该substringToIndex()
函数,使其长度比的长度少一String
:
let name: String = "Dolphin"
name.substringToIndex(countElements(name) - 1) // "Dolphi"
substringToIndex
substringToIndex
不是substringFromIndex
。让我告诉你,这不会让你感到聪明。
substringToIndex
。此外,从Xcode 7开始,字符串不再具有.count
属性,现在仅适用于字符:string.characters.count
var truncated = name.substring(to: name.index(before: name.endIndex))
全局dropLast()
函数适用于序列,因此适用于字符串:
var expression = "45+22"
expression = dropLast(expression) // "45+2"
// in Swift 2.0 (according to cromanelli's comment below)
expression = String(expression.characters.dropLast())
characters
字符串的属性输出一个序列,因此,您现在必须使用: expression = expression.characters.dropLast()
expression = String(expression.characters.dropLast())
如果您想将结果作为字符串返回,则必须正确地转换结果
这是一个字符串扩展形式:
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))
}
}
对于低于1.2的Swift版本:
...
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扩展没有名称。)
见DOCS
使用功能removeAtIndex(i: String.Index) -> Character
:
var s = "abc"
s.removeAtIndex(s.endIndex.predecessor()) // "ab"
修剪字符串的最后一个字符的最简单方法是:
title = title[title.startIndex ..< title.endIndex.advancedBy(-1)]
var str = "Hello, playground"
extension String {
var stringByDeletingLastCharacter: String {
return dropLast(self)
}
}
println(str.stringByDeletingLastCharacter) // "Hello, playgroun"
迅速变化的类别:
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年4月16日起有效): removeAtIndex(myString.endIndex.predecessor())
例:
var howToBeHappy = "Practice compassion, attention and gratitude. And smile!!"
howToBeHappy.removeAtIndex(howToBeHappy.endIndex.predecessor())
println(howToBeHappy)
// "Practice compassion, attention and gratitude. And smile!"
元:
该语言继续快速发展,使得许多以前不错的SO答案的半衰期非常短暂。最好总是学习该语言并参考实际文档。
使用新的Substring类型用法:
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
我建议对要操作的字符串使用NSString。实际上,以开发人员的身份来思考它,我从未遇到过Swift String可以解决的NSString问题...我了解这些细微之处。但是我还没有他们的实际需求。
var foo = someSwiftString as NSString
要么
var foo = "Foo" as NSString
要么
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)
该dropLast()
函数删除字符串的最后一个元素。
var expression = "45+22"
expression = expression.dropLast()
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
}
}
斯威夫特4.2
我也从IOS应用程序中的String(即UILabel text)中删除了我的最后一个字符
@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
}
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
补充上面的代码,我想删除字符串的开头,并且在任何地方都找不到引用。这是我的做法:
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,就可以了。