var domains = "abcde".substring(0,"abcde".indexOf("cd")) // Returns "ab"
Swift没有这个功能,怎么做类似的事情?
Xcode 8.3.1•Swift 3.1extension String { func index(of string: String,options: CompareOptions = .literal) -> Index? { return range(of: string,options: options)?.lowerBound } func endindex(of string: String,options: options)?.upperBound } func indexes(of string: String,options: CompareOptions = .literal) -> [Index] { var result: [Index] = [] var start = startIndex while let range = range(of: string,options: options,range: start..<endindex) { result.append(range.lowerBound) start = range.upperBound } return result } func ranges(of string: String,options: CompareOptions = .literal) -> [Range<Index>] { var result: [Range<Index>] = [] var start = startIndex while let range = range(of: string,range: start..<endindex) { result.append(range) start = range.upperBound } return result }}
用法:
let str = "Hello,playground,playground"str.index(of: "play") // 7str.endindex(of: "play") // 11str.indexes(of: "play") // [7,19,31]str.ranges(of: "play") // [{lowerBound 7,upperBound 11},{lowerBound 19,upperBound 23},{lowerBound 31,upperBound 35}]总结
以上是内存溢出为你收集整理的使用Swift的字符串中的子字符串索引全部内容,希望文章能够帮你解决使用Swift的字符串中的子字符串索引所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)