func test() {
let str = "0123456789"
//查找
//查找索引从0开始的开区间
print(str.range(of: "0")) //0..<1
if let range = str.range(of: "9") {
print(range)//9..<10
//截取
//使用带限制在索引内的检索(limitedBy),超出限制索引时返回nil(推荐使用这个方法)
if let index = str.index(range.lowerBound, offsetBy: 3, limitedBy: str.endIndex) {
print(index)//nil
}
//使用不带限制检索时,如果检索结果超过字符串本身长度会报异常
// let index = str.index(range.lowerBound, offsetBy: 3)
// print(index)
}
}
//查找和替换,将字符串中的'/(任意字符串).ts'替换为'--'
//1.找出需要替换的字符串所在范围,2.替换它
func test1() {
var str = "/hls/1480672715/183_3105_177223685/low8.ts?key=1481207079-0-0-78f7475aaa6b1e0e60d3655fe10bd6a1"
//先查找'.ts'
let range = str.range(of: ".ts")
//重新设置查找范围
let tmp = str.startIndex..<range!.lowerBound
//反向查找'/'
let range1 = str.range(of: "/", options: .backwards, range: tmp, locale: nil)
//最终确定需要替换的字符串所在索引范围
let resultRange = range1!.lowerBound..<range!.upperBound
print(str.substring(with: resultRange))//'/low8.ts'
str.replaceSubrange(resultRange, with: "--")
print(str)//'/hls/1480672715/183_3105_177223685--?key=1481207079-0-0-78f7475aaa6b1e0e60d3655fe10bd6a1'
}
网友评论