iOS 查找字符串出现的范围
作者:新一
- 2022-12-02 山东
本文字数:770 字
阅读完需:约 3 分钟
swift 中查找字符串出现的位置,返回一个数组格式,直接上代码吧
因为字数不到 50 字,不能发表,那我就说一下应用场景吧:
主要就是对富文本的操作,比如,文本里 @的人名字需要更改颜色,字体
let test1: String = "这是铁子你说对不说对铁好说对"
let test2 = "铁子"
let test3 = "子"
let test4 = "哈哈"
let test5 = "😁"
let test6 = "说对"
extension String {
func nsranges(of substring: String, options: CompareOptions = [], locale: Locale? = nil) -> [NSRange] {
let totalLength = NSString(string: self).length
var ranges: [NSRange] = []
var lastLocation = 0
var lastLength = 0
var currentLocation = 0
var leftLength = totalLength
while leftLength >= NSString(string: substring).length {
let targetRange = NSRange(location: currentLocation, length: leftLength)
let range = NSString(string: self).range(of: substring, options: options, range: targetRange, locale: locale)
if range.location + range.length > totalLength {
break
}
ranges.append(range)
lastLocation = ranges.last?.location ?? 0
lastLength = ranges.last?.length ?? 0
currentLocation = lastLocation + lastLength
leftLength = totalLength - currentLocation
}
return ranges
}
}
print(test1.nsranges(of: test2, options: .caseInsensitive))
print(test1.nsranges(of: test3, options: .caseInsensitive))
print(test1.nsranges(of: test4, options: .caseInsensitive))
print(test1.nsranges(of: test5, options: .caseInsensitive))
print(test1.nsranges(of: test6, options: .caseInsensitive))
//打印结果
//[{2, 2}]
//[{3, 1}]
//[]
//[]
//[{5, 2}, {8, 2}, {12, 2}]
复制代码
划线
评论
复制
发布于: 刚刚阅读数: 5
新一
关注
还未添加个人签名 2018-11-15 加入
还未添加个人简介
评论