标签:style blog http io color os ar sp div
在Swift中,当我们想要截取某个字符串时,方法如下:
let carNumber = "沪A12345" let startIndex = advance(userCar.carPlateNumber.startIndex, 0) let endIndex = advance(startIndex, 1) let range = startIndex..<endIndex println(carNumber[range]) // 输出沪
呃,好怀念substring方法啊,那我们就自己实现一个吧。
extension String { subscript (r: Range<Int>) -> String { get { let startIndex = advance(self.startIndex, r.startIndex) let endIndex = advance(startIndex, r.endIndex - r.startIndex) return self[Range(start: startIndex, end: endIndex)] } } }
调用很简单,示例如下:
var s = "Hello, playground" println(s[0...5]) // ==> "Hello," println(s[0..<5]) // ==> "Hello"
感谢Rob Napier http://stackoverflow.com/questions/24044851/how-do-you-use-string-substringwithrange-or-how-do-ranges-work-in-swift
标签:style blog http io color os ar sp div
原文地址:http://www.cnblogs.com/ilovewindy/p/4065749.html