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

编程入门 行业动态 更新时间:2024-10-24 13:29:28
本文介绍了Swift 字符串中子字符串的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我习惯于在 JavaScript 中执行此操作:

I'm used to do this in JavaScript:

var domains = "abcde".substring(0, "abcde".indexOf("cd")) // Returns "ab"

Swift 没有这个功能,怎么做类似的?

Swift doesn't have this function, how to do something similar?

推荐答案

编辑/更新:

Xcode 11.4 • Swift 5.2 或更高版本

import Foundation extension 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] { ranges(of: string, options: options).map(\.lowerBound) } 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) // "ab\n" }

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

不区分大小写的示例


case insensitive sample

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

正则表达式示例


regular expression sample

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

更多推荐

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

本文发布于:2023-10-19 14:53:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1507853.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   中子   索引   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!