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
16
17
18
19
20
21
22
23
24
25
26
// 第3位开始
let start = str.index(str.startIndex, offsetBy: 3)
// 倒数第二位
let end = str.index(str.endIndex, offsetBy: -2)
let result = str[start...end] // 3-8

// substr range
// range
let range = start ..< end
range.lowerBound // 3
range.upperBound // 8
str.substring(with: range) // 3-8

str[...start] // 0-3
str.prefix(through: start)

str[start...] // 3-9
str.suffix(from: start)

// 字符查找
let indofs = str.index(of: "2")!
var indofe = str.index(of: "8")!
// 截取
str[indofs...indofe] // 2-8
indofe = str.index(indofs, offsetBy: 2)
str[indofs...indofe] // 2-4

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)

本文标题:Swift3 截取字符串

文章作者:史彦超

发布时间:2016年10月11日 - 22:10

最后更新:2021年07月20日 - 16:07

原始链接:https://doingself.github.io/2016/10/11/2016-10-11-Swift3%E6%88%AA%E5%8F%96%E5%AD%97%E7%AC%A6%E4%B8%B2/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Donate comment here