Swift-SubString

Swift SubString 操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import Foundation

extension String {
subscript(value: PartialRangeUpTo<Int>) -> Substring {
get {
return self[..<index(startIndex, offsetBy: value.upperBound)]
}
}

subscript(value: PartialRangeThrough<Int>) -> Substring {
get {
return self[...index(startIndex, offsetBy: value.upperBound)]
}
}

subscript(value: PartialRangeFrom<Int>) -> Substring {
get {
return self[index(startIndex, offsetBy: value.lowerBound)...]
}
}

subscript(value: CountableRange<Int>) -> Substring {
get {
let start = index(self.startIndex, offsetBy: value.lowerBound)
let end = index(self.startIndex, offsetBy: value.upperBound)
return self[start..<end]
}
}

subscript(value: ClosedRange<Int>) -> Substring {
get {
let start = index(self.startIndex, offsetBy: value.lowerBound)
let end = index(self.startIndex, offsetBy: value.upperBound)
return self[start...end]
}
}
}

let str = "hello"
// PartialRangeFrom
print(str[1...]) // ello
// PartialRangeThrough
print(str[...3]) // hell
// PartialRangeUpTo
print(str[..<3]) // hel
// ClosedRange
print(str[1...3]) // ell
// CountableRange
print(str[1..<3]) // el
-------------本文结束感谢您的阅读-------------