ios 删除字符串中的最后两个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40028035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove Last Two Characters in a String
提问by Ben
Is there a quick way to remove the last two characters in a String in Swift? I see there is a simple way to remove the last character as clearly noted here. Do you know how to remove the last two characters? Thanks!
有没有一种快速的方法可以在 Swift 中删除字符串中的最后两个字符?我看到有一种简单的方法可以删除最后一个字符,正如此处明确指出的那样。你知道如何删除最后两个字符吗?谢谢!
回答by Leo Dabus
update: Xcode 9 ? Swift 4 or later
更新:Xcode 9?Swift 4 或更高版本
String now conforms to RangeReplaceableCollection so you can use collection method dropLast straight in the String and therefore an extension it is not necessary anymore. The only difference is that it returns a Substring. If you need a String you need to initialize a new one from it:
String 现在符合 RangeReplaceableCollection,因此您可以直接在 String 中使用集合方法 dropLast,因此不再需要扩展。唯一的区别是它返回一个子字符串。如果您需要一个字符串,则需要从中初始化一个新字符串:
let string = "0123456789"
let substring1 = string.dropLast(2) // "01234567"
let substring2 = substring1.dropLast() // "0123456"
let result = String(substring2.dropLast()) // "012345"
We can also extend LosslessStringConvertible
to add trailing syntax which I think improves readability:
我们还可以扩展LosslessStringConvertible
添加尾随语法,我认为这可以提高可读性:
extension LosslessStringConvertible {
var string: String { .init(self) }
}
Usage:
用法:
let result = substring.dropLast().string
回答by Naveen Ramanathan
var name: String = "Dolphin"
let endIndex = name.index(name.endIndex, offsetBy: -2)
let truncated = name.substring(to: endIndex)
print(name) // "Dolphin"
print(truncated) // "Dolph"
回答by Deepak Tagadiya
swift 4:
快速4:
let str = "Hello, playground"
let newSTR1 = str.dropLast(3)
print(newSTR1)
output: "Hello, playgro"
//---------------//
let str = "Hello, playground"
let newSTR2 = str.dropFirst(2)
print(newSTR2)
output: "llo, playground"
回答by Andy Obusek
Use removeSubrange(Range<String.Index>)
just like:
使用removeSubrange(Range<String.Index>)
就像:
var str = "Hello, playground"
str.removeSubrange(Range(uncheckedBounds: (lower: str.index(str.endIndex, offsetBy: -2), upper: str.endIndex)))
This will crash if the string is less than 2 characters long. Is that a requirement for you?
如果字符串少于 2 个字符,这将崩溃。这对你有要求吗?
回答by Guillaume Ramey
Better to use removeLast()
最好使用removeLast()
var myString = "Hello world"
myString.removeLast(2)
output : "Hello wor"