栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Swift字符串中子字符串的索引

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Swift字符串中子字符串的索引

编辑/更新:

Xpre 11•Swift 5.1或更高版本

import Foundationextension StringProtocol {    func index<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> Index? {        range(of: string, options: options)?.lowerBound    }    func endIndex<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> Index? {        range(of: string, options: options)?.upperBound    }    func indices<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> [Index] {        var indices: [Index] = []        var startIndex = self.startIndex        while startIndex < endIndex, let range = self[startIndex...]     .range(of: string, options: options) {     indices.append(range.lowerBound)     startIndex = range.lowerBound < range.upperBound ? range.upperBound :         index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex        }        return indices    }    func ranges<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> [Range<Index>] {        var result: [Range<Index>] = []        var startIndex = self.startIndex        while startIndex < endIndex, let range = self[startIndex...]     .range(of: string, options: options) {     result.append(range)     startIndex = range.lowerBound < range.upperBound ? range.upperBound :         index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex        }        return result    }}

用法:

let str = "abcde"if let index = str.index(of: "cd") {    let substring = str[..<index]   // ab    let string = String(substring)    print(string)  // "abn"}

let str = "Hello, playground, playground, playground"str.index(of: "play")      // 7str.endIndex(of: "play")   // 11str.indices(of: "play")    // [7, 19, 31]str.ranges(of: "play")     // [{lowerBound 7, upperBound 11}, {lowerBound 19, upperBound 23}, {lowerBound 31, upperBound 35}]

不区分大小写的样本

let query = "Play"let ranges = str.ranges(of: query, options: .caseInsensitive)let matches = ranges.map { str[$0] }   //print(matches)  // ["play", "play", "play"]

正则表达式样本

let query = "play"let escapedQuery = NSRegularexpression.escapedPattern(for: query)let pattern = "\b(escapedQuery)\w+"  // matches any word that starts with "play" prefixlet ranges = str.ranges(of: pattern, options: .regularexpression)let matches = ranges.map { str[$0] }print(matches) //  ["playground", "playground", "playground"]


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/623977.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号