在Swift String中查找字符的索引

在Swift String中查找字符的索引,第1张

在Swift String中查找字符索引

您不是唯一找不到解决方案的人。

String
没有实现
RandomAccessIndexType
。可能是因为它们启用了具有不同字节长度的字符。这就是为什么我们必须使用
string.characters.count
count
countElements
在Swift
1.x中)获取字符数的原因。这也适用于职位。的
_position
可能是一个索引字节的原始阵列,他们不希望公开这一点。本
String.Index
是为了保护我们从人物的中间访问字节。

这意味着您必须从

String.startIndex
String.endIndex
String.Index
实现
BidirectionalIndexType
)创建任何索引。可以使用
successor
predecessor
方法创建任何其他索引。

现在可以使用索引来帮助我们,它提供了一组方法(Swift 1.x中的函数):

斯威夫特4.x

let text = "abc"let index2 = text.index(text.startIndex, offsetBy: 2) //will call succ 2 timeslet lastChar: Character = text[index2] //now we can index!let characterIndex2 = text.index(text.startIndex, offsetBy: 2)let lastChar2 = text[characterIndex2] //will do the same as abovelet range: Range<String.Index> = text.range(of: "b")!let index: Int = text.distance(from: text.startIndex, to: range.lowerBound)

斯威夫特3.0

let text = "abc"let index2 = text.index(text.startIndex, offsetBy: 2) //will call succ 2 timeslet lastChar: Character = text[index2] //now we can index!let characterIndex2 = text.characters.index(text.characters.startIndex, offsetBy: 2)let lastChar2 = text.characters[characterIndex2] //will do the same as abovelet range: Range<String.Index> = text.range(of: "b")!let index: Int = text.distance(from: text.startIndex, to: range.lowerBound)

斯威夫特2.x

let text = "abc"let index2 = text.startIndex.advancedBy(2) //will call succ 2 timeslet lastChar: Character = text[index2] //now we can index!let lastChar2 = text.characters[index2] //will do the same as abovelet range: Range<String.Index> = text.rangeOfString("b")!let index: Int = text.startIndex.distanceTo(range.startIndex) //will call successor/predecessor several times until the indices match

斯威夫特1.x

let text = "abc"let index2 = advance(text.startIndex, 2) //will call succ 2 timeslet lastChar: Character = text[index2] //now we can index!let range = text.rangeOfString("b")let index: Int = distance(text.startIndex, range.startIndex) //will call succ/pred several times

使用

String.Index
它很麻烦,但是使用包装器按整数索引很危险,因为它掩盖了实际索引的效率低下。

请注意,Swift索引实现存在一个问题,即为 一个字符串创建的索引/范围不能可靠地用于其他字符串 ,例如:

斯威夫特2.x

let text: String = "abc"let text2: String = "					
										


					

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5013045.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-14
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存