Swift 3 中String 的取子串

翻译自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

  • startIndex 是第一个字符的索引, 也就是
  • endIndex 是最后一个字符索引 +1
// 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 中的代码就会跳过

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

  • 取某个位置之后的所有字符
    str.substring(from: str.index(str.startIndex, offsetBy: 7)) // playground
  • 取倒数某个位置之后的所有字符
    str.substring(from: str.index(str.endIndex, offsetBy: -10)) //playground
  • 取某个位置之前的所有字符
    str.substring(to: str.index(str.startIndex, offsetBy: 5)) //Hello
  • 取倒数某个位置之前的所有字符
    str.substring(to: str.index(str.endIndex, offsetBy: -12)) //Hello
  • 取中间的某个字符串
    str.substring(with: str.index(str.startIndex, offsetBy: 7) ..< str.index(str.endIndex, offsetBy: -6)) // play
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift 中的字符串截取 发表于2016-12-14||100 Substring in Swift 3.0 I...
    762683ff5d3d阅读 2,748评论 0 0
  • java中String的常用方法 1、length()字符串的长度 例:char chars[]={'a','b'...
    赤赤有名阅读 2,121评论 0 10
  • 父亲的情怀 文/与你相识 在原地守望 那些碎落的青春和微笑 蹒跚的步履里 总有一个温暖的怀抱 青春或许会老去 你有...
    与你相识_40fa阅读 281评论 3 4
  • 图文/无为跑者 仰望榄仁宽且直, 喜观某人乐充实。 开花绝非就结果, 愿尔无获亦能持。
    最家游阅读 1,227评论 12 28
  • 事不能拖,话不能多,人不能作。与你无关的事,别问,别想,别说。 ​会说话是修养,管住嘴是教养。聪明的人懂得在外守嘴...
    与茶有缘阅读 365评论 0 3