#indices
通过indices可以拿到string的每个元素
1
2
3
4
let str1 = "123456890"
for a in str1.indices {
print(a.utf16Offset(in: str1))
}
拿到指定的first or last
str1[str1.indices.first!]
str1[str1.indices.last!]
通过协议实现,可以拿到指定元素在string 中的下标
1
2
3
4
5
6
7
8
fileprivate extension String {
func indexOf(char: Character) -> Int? {
return firstIndex(of: char)?.utf16Offset(in: self)
}
}
let t = str1.indexOf(char: "3")
print(t ?? 0)
分割string
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// String分割一般用 ..< 例:string.startIndex..<string.endInde
var str2 = "Hello,playground"
let range = str2.index(str2.startIndex, offsetBy: 0) ..< str2.index(str2.endIndex, offsetBy: -11)
str2[range]
// 获取字符串内容字符串长度不确定,获取长度大于字符串长度时,返回整串,目标长度小于字符串长度返回截取的子串内容
var length = 10
var contentRange: Range<String.Index>
if let content = str2.index(str2.startIndex, offsetBy: length, limitedBy: str2.endIndex) {
contentRange = str2.index(str2.startIndex, offsetBy: 0) ..< str2.index(content, offsetBy: 0)
} else {
contentRange = str2.index(str2.startIndex, offsetBy: 0) ..< str2.index(str2.endIndex, offsetBy: 0)
}
str2[contentRange]