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,869評論 18 139
  • String是例如"hello, world","albatross"這樣的有序的Character(字符)類型的...
    窮人家的孩紙閱讀 865評論 2 1
  • 一個字符串 是一系列字符的集合,例如hello, world和albatross。Swift的字符串是String...
    BoomLee閱讀 2,421評論 0 3
  • 做網賺做微商的離不開流量粉絲這個話題,銷售的本質簡單說就是流量+轉化,小白們每天不知疲憊的穿梭于各個微信群,貼吧,...
    檸檬Lynn閱讀 1,307評論 0 0
  • 曾經愛上自拍的我,現在卻不敢直視對面的鏡子。我怕舍友打我,我怕老子照破鏡。 直到那天晚上下著雨,閃著雷。舍...
    筆斷流閱讀 282評論 0 2