swift3 截取字符串

1
2
// 截取字符串
let str = "0123456789"

substring from

1
2
3
// substr from 从第4位开始截取
// 456789
str.substring(from: str.index(str.startIndex, offsetBy: 4))

substring to

1
2
3
// substr to 截取前3位
// 012
str.substring(to: str.index(str.startIndex, offsetBy: 3))

substring Range

index

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// substr range
// 从第3位开始
// 3
let start = str.index(str.startIndex, offsetBy: 3)
// 倒数4位
// 6
let end = str.index(str.endIndex, offsetBy: -4)
// range
let range = start ..< end
// 3
range.lowerBound
// 6
range.upperBound
// 345
str.substring(with: range)

range of

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// substr range 
let text = "0,2,4,6,"
// 从后到前找到第一个字符的range
let endRange = text.range(of: ",", options: .backwards, range: nil, locale: nil)
// 7
endRange?.lowerBound
// 8
endRange?.upperBound
// 根据 ..< 创建range
let searchRange = text.startIndex ..< (endRange?.lowerBound)!
// 0
searchRange.lowerBound
// 7
searchRange.upperBound
// 截取字符串
// 0,2,4,6
text.substring(with: searchRange)