iOS开发swift

Swift 3 中String 的取子串

2017-01-23  本文已影响1476人  yww

翻译自How does String.Index work in Swift 3

swift 中关于取子串有4 个方法

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)

分别是什么, 该如何使用?
下面来看看
本例中, 我们创建一个字符串"Hello, playground" , 如下

var str = "Hello, playground"
字符索引

startIndex 和 endIndex

// character
str[str.startIndex] // H
str[str.endIndex]   // error: after last character

// range
let range = str.startIndex ..< str.endIndex
str[range]  // "Hello, playground"

after

index(after: String.Index)
after 指向给定索引后面的一个索引(类似与 + 1)

// 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"

before

index(before: String.Index)
before 指向给定索引之前的一个索引(类似与 - 1)

// 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 的值可以为正或是负, 正则表示向后, 负则相反.别被offsetBy 的 String.IndexDistance 类型吓到, 本身其实是一个 Int.(类似于+n 和 -n)

// 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, limitedBy: String.Index)

limitedBy 在 offset 过大导致溢出错误的时候很有用.这个返回值是一个可选值, 如果 offsetBy 超过了 limitBy, 则返回 nil.

// character
if let index = str.index(str.startIndex, offsetBy: 7, limitedBy: str.endIndex) {
    str[index]  // p
}

上面这段代码中如果offset 设置为 77, 返回值就是 nil, if 中的代码就会跳过

所以如果你要取子串的正确姿势是什么?

上一篇 下一篇

猜你喜欢

热点阅读