iOS - Swift 实现字符串查找子字符串的位置
需求:从一串字符串中查找子字符串的位置
实现:系统框架中并没有可以直接调用的方法直接获取子字符串开始的位置,需要以下几步即可获取到子字符串的起始位置。
应用场景:比如我们要对 UILabel 的文本中的部分字符标记,那么我们就需要找出来要标记的文本的位置,结合文本的长度,我们就可以实现标记
第一步:我们需要借助下面的这个方法来获取位置
参数是两个索引,如果要获取子字符串的起始位置,只需要传递父字符串的开始索引和子字符串在父字符串中的开始索引。第一个参数就是 str.startIndex,第二个参数需要第二步中的方法获取到
/// Returns the distance between two indices. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. /// /// - Complexity: O(*n*), where *n* is the resulting distance. @inlinable public func distance(from start: String.Index, to end: String.Index) -> String.IndexDistance
第二步:获取子字符串在父字符串中的范围 (Rang: 是一个半开放的区间,不包含最大值)。
获取到 Range 后,需要把得到的 Rang.lowerBound 传递到第一步方法中的第二个参数中,我们就获取到了子字符串在父字符串中的位置。
str.range(of:)
示例:
let helloWorld: String = "Hello World" let wo: String = "Wo" let range: Range = helloWorld.range(of: wo)! let location = helloWorld.distance(from: helloWorld.startIndex, to: range.lowerBound)
// location: 6
最后我们可以得到 location 的值为 6
自律 平静 思考 实践
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端