LoginSignup
1
1

More than 5 years have passed since last update.

Swift で substring

Posted at

Swift の substring は引数が Int ではなく Index となっていて、Index の作り方がわからなくて調べたのでメモ。

// str の 4 文字目から 5 文字分取り出すサンプル

let str = "0123456789"
let index = 3
let length = 5

// `Index` を作る
let start = str.startIndex.advancedBy(index) // => 3
let end = start.advancedBy(length) // => 8
// `Range` を作る
let range = start..<end // => 3..<8

let substr1 = str.substringWithRange(range) // => "34567"
let substr2 = str[range] // => "34567"
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1