メモ程度の内容です。
文字列の一部を抽出するとき、Kotlinではslice()
やsubstring()
を使うかと思います。
特に文字列の先頭や末尾からn文字を抽出することはよくあると思いますが、そのときにtake()
とtakeLast()
というメソッドを使うと便利でした。
- https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/take.html
- https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/take-last.html
使い方は以下のように至ってシンプルです。
val alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
println(alphabet.take(7))
// => ABCDEFG
println(alphabet.takeLast(5))
// => VWXYZ
// 文字列の長さを超える値(この例では27以上)を引数に指定したときは、元の文字列が返却される
println(alphabet.take(30))
println(alphabet.takeLast(30))
// => ABCDEFGHIJKLMNOPQRSTUVWXYZ
// マイナスの値を引数に指定したときは、実行時にIllegalArgumentExceptionがthrowされる
println(alphabet.take(-1))
println(alphabet.takeLast(-1))
// => IllegalArgumentException: Requested character count -1 is less than zero.