swift 字符串学习 (index用法和截取)

let character = "abcdefghijklmn"
// 获取字符串第一个字符
character[character.startIndex]
character.characters.first
// 获取字符串最后一个字符
let endIndex = character.endIndex // 14
// character[endIndex] // endIndex 直接用endIndex会越界,因为endIndex得到的index是字符串的长度,而字符串截取是从下标0开始的,这样直接用会越界
// 想要获取字符串最后一位
character[character.index(before: character.endIndex)]
character.characters.last
 // offset 从指定位置开始,偏移多少位(正负均可)
character[character.index(character.startIndex, offsetBy: 4)]
// 用法跟 character.index(, offsetBy: ) 一样,只不过这个做了越界校验,limitedBy填入越界限制.
// 这个方法返回值是个可选的,如果offsetBy的参数大于limitedBy做的限制就会返回nil
let limited = character.index(character.endIndex, offsetBy: -1)
character.index(character.startIndex, offsetBy: 14, limitedBy: limited)
 // after 指定位置之后一位
character[character.index(after: character.startIndex)]
character[character.index(after: character.index(character.startIndex, offsetBy: 2))]
 // before 指定位置之前的一位
character[character.index(before: character.endIndex)]
character[character.index(before: character.index(character.endIndex, offsetBy: -2))]
// 字符串截取
let range = character.startIndex ..< character.index(character.startIndex, offsetBy: 3)
character[range]
character.substring(with: range)

给String写个扩展

extension String {
  public subscript(bounds: CountableRange<Int>) -> String {

    let string = self[index(startIndex, offsetBy: bounds.lowerBound) ..< index(startIndex, offsetBy: bounds.upperBound)]
    return string
  }
  
  public subscript(bounds: CountableClosedRange<Int>) -> String {
    let string = self[index(startIndex, offsetBy: bounds.lowerBound) ... index(startIndex, offsetBy: bounds.upperBound)]
    return string
  }
  
  public subscript(index: Int) -> String {
    let character = self[self.index(startIndex, offsetBy: index)]
    return String(character)
  }
}

用法:

character[3 ..< 14]
character[3 ... 14]
character[1]
character[14]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • String是例如"hello, world","albatross"这样的有序的Character(字符)类型的...
    穷人家的孩纸阅读 865评论 2 1
  • 一个字符串 是一系列字符的集合,例如hello, world和albatross。Swift的字符串是String...
    BoomLee阅读 2,423评论 0 3
  • 做网赚做微商的离不开流量粉丝这个话题,销售的本质简单说就是流量+转化,小白们每天不知疲惫的穿梭于各个微信群,贴吧,...
    柠檬Lynn阅读 1,322评论 0 0
  • 曾经爱上自拍的我,现在却不敢直视对面的镜子。我怕舍友打我,我怕老子照破镜。 直到那天晚上下着雨,闪着雷。舍...
    笔断流阅读 283评论 0 2