Swift 3中截取字符串的方法有substring(with: Range<String.Index>
, substring(to: String.Index)
, substring(from: String.Index)
这三个方法。
使用的方法如下:
let text = "This is a text string"
let start = text.index(text.startIndex, offsetBy: 4)
let a = text.substring(from: start)
let b = text.substring(to: start)
let end = text.index(text.startIndex, offsetBy: 8)
let c = text.substring(with: Range(uncheckedBounds: (start, end)))
print("a: \(a)")
print("b: \(b)")
print("c: \(c)")
复制代码
输出结果如下:
a: is a text string
b: This
c: is
复制代码
因为String.Index
类型不是我们之前用的Int
类型,所以截取字符串的话会有较多的代码量
如果觉得每次获取都要写一堆index比较麻烦的话,也可以使用extension
来扩展String
的subscript
e.g:
extension String {
subscript(r: Range<Int>) -> String {
get {
let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
let endIndex = self.index(self.startIndex, offsetBy: r.upperBound+1)
return self[Range(uncheckedBounds: (startIndex, endIndex))]
}
}
subscript(start: Int, end: Int) -> String {
get {
let startIndex = self.index(self.startIndex, offsetBy: start)
let endIndex = self.index(self.startIndex, offsetBy: end+1)
return self[Range(uncheckedBounds: (startIndex, endIndex))]
}
}
}
复制代码