String.Index在Swift 3中如何工作
我已经使用Swift 3更新了一些旧的代码和答案,但是当我进入Swift Strings和Indexing时,很难理解它。
具体来说,我正在尝试以下几点: let str = "Hello,playground" let prefixRange = str.startIndex..<str.startIndex.advancedBy(5) // error 第二行给我以下错误
我看到String有以下方法。 str.index(after: String.Index) str.index(before: String.Index) str.index(String.Index,offsetBy: String.IndexDistance) str.index(String.Index,offsetBy: String.IndexDistance,limitedBy: String.Index) 这些真的让我很困惑,所以我开始玩弄他们,直到我理解他们为止。我在下面添加一个答案来展示如何使用它们。 以下所有示例都使用 var str = "Hello,playground" startIndex和endIndex > startIndex是第一个字符的索引 例 // character str[str.startIndex] // H str[str.endIndex] // error: after last character // range let range = str.startIndex..<str.endIndex str[range] // "Hello,playground" 后 如下:index(after:String.Index) >之后直接指向给定索引后的字符索引。 例子 // character let index = str.index(after: str.startIndex) str[index] // "e" // range let range = str.index(after: str.startIndex)..<str.endIndex str[range] // "ello,playground" 之前 如下:index(before:String.Index) > before指的是直接在给定索引之前的字符的索引。 例子 // character let index = str.index(before: str.endIndex) str[index] // d // range let range = str.startIndex..<str.index(before: str.endIndex) str[range] // Hello,playgroun offsetBy 如下:index(String.Index,offsetBy:String.IndexDistance) > offsetBy值可以为正或负,并从给定索引开始。虽然它是String.IndexDistance类型,可以给它一个Int。 例子 // character let index = str.index(str.startIndex,offsetBy: 7) str[index] // p // range let start = str.index(str.startIndex,offsetBy: 7) let end = str.index(str.endIndex,offsetBy: -6) let range = start..<end str[range] // play limitedBy 如下:index(String.Index,offsetBy:String.IndexDistance,restrictedBy:String.Index) > limitedBy对于确保偏移量不会导致索引超出范围是有用的。这是一个有界的指数。由于偏移量可能超过限制,此方法返回可选。如果索引超出范围,则返回nil。 例 // character if let index = str.index(str.startIndex,offsetBy: 7,limitedBy: str.endIndex) { str[index] // p } 如果偏移量是77而不是7,那么if语句将被跳过。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |