茶漬けの技術メモ

Golang, Rubyで趣味開発します。テックニュース書いたり。ガジェット触ったり。

Swiftで文字列から部分的に文字列を取得する

Swift3.0で文字列から部分的に文字列を取得するには、substringを使いますが、その際引数にはIntではなく、Indexを使う必要があります。

let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

// 先頭から10文字取り出す
alphabet.substring(to: alphabet.index(alphabet.startIndex, offsetBy: 10))
// "ABCDEFGHIJ"

// 最後の10文字を取り出す
alphabet.substring(from: alphabet.index(alphabet.endIndex, offsetBy: -10))
// "QRSTUVWXYZ"

// 指定した範囲の文字列取得
alphabet.substring(with: alphabet.index(alphabet.startIndex, offsetBy: 10)..<alphabet.index(alphabet.endIndex, offsetBy: -10))
// "KLMNP"

// 指定した範囲の文字列取得
alphabet[alphabet.index(alphabet.startIndex, offsetBy: 10)..<alphabet.index(alphabet.endIndex, offsetBy: -10)]
// "KLMNP"


Indexの取得は以下のようにできます

alphabet.startIndex
// 0

alphabet.endIndex
// 26

alphabet.index(alphabet.startIndex, offsetBy: 10)
// 10

alphabet.index(alphabet.endIndex, offsetBy: -10)
// 16


Indexが文字列範囲内にあればIndexを返し、文字列範囲外であればnilを返す

alphabet.index(alphabet.startIndex, offsetBy:26, limitedBy: alphabet.endIndex)
// 26

alphabet.index(alphabet.startIndex, offsetBy:27, limitedBy: alphabet.endIndex)
// nil