Swift 4 更新
在 Swift 4 中,String 再次符合Collection,因此可以使用dropFirst 和dropLast 来修剪字符串的开头和结尾。结果是Substring 类型,因此您需要将其传递给String 构造函数以取回String:
let str = "hello"
let result1 = String(str.dropFirst()) // "ello"
let result2 = String(str.dropLast()) // "hell"
dropFirst() 和 dropLast() 也采用 Int 来指定要删除的字符数:
let result3 = String(str.dropLast(3)) // "he"
let result4 = String(str.dropFirst(4)) // "o"
如果您指定要删除的字符多于字符串中的字符,则结果将是空字符串 ("")。
let result5 = String(str.dropFirst(10)) // ""
Swift 3 更新
如果您只想删除第一个字符并想更改原始字符串,请参阅@MickMacCallum 的答案。如果要在此过程中创建新字符串,请使用substring(from:)。使用String 的扩展名,您可以隐藏substring(from:) 和substring(to:) 的丑陋之处,以创建有用的补充来修剪String 的开头和结尾:
extension String {
func chopPrefix(_ count: Int = 1) -> String {
return substring(from: index(startIndex, offsetBy: count))
}
func chopSuffix(_ count: Int = 1) -> String {
return substring(to: index(endIndex, offsetBy: -count))
}
}
"hello".chopPrefix() // "ello"
"hello".chopPrefix(3) // "lo"
"hello".chopSuffix() // "hell"
"hello".chopSuffix(3) // "he"
像之前的dropFirst 和dropLast 一样,如果字符串中没有足够的可用字母,这些函数将崩溃。调用者有责任正确使用它们。这是一个有效的设计决策。可以编写它们以返回一个可选的,然后必须由调用者解包。
Swift 2.x
唉,Swift 2、dropFirst 和 dropLast(之前的最佳解决方案)不像以前那么方便了。通过String的扩展,可以隐藏substringFromIndex和substringToIndex的丑陋之处:
extension String {
func chopPrefix(count: Int = 1) -> String {
return self.substringFromIndex(advance(self.startIndex, count))
}
func chopSuffix(count: Int = 1) -> String {
return self.substringToIndex(advance(self.endIndex, -count))
}
}
"hello".chopPrefix() // "ello"
"hello".chopPrefix(3) // "lo"
"hello".chopSuffix() // "hell"
"hello".chopSuffix(3) // "he"
与之前的dropFirst 和dropLast 一样,如果字符串中没有足够的可用字母,这些函数将崩溃。调用者有责任正确使用它们。这是一个有效的设计决策。可以编写它们以返回一个可选的,然后必须由调用者解包。
在 Swift 1.2 中,您需要像这样调用chopPrefix:
"hello".chopPrefix(count: 3) // "lo"
或者您可以在函数定义中添加下划线_ 以隐藏参数名称:
extension String {
func chopPrefix(_ count: Int = 1) -> String {
return self.substringFromIndex(advance(self.startIndex, count))
}
func chopSuffix(_ count: Int = 1) -> String {
return self.substringToIndex(advance(self.endIndex, -count))
}
}