15
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Kotlinで文字列の先頭や末尾からn文字を抽出する

Last updated at Posted at 2020-07-27

メモ程度の内容です。

文字列の一部を抽出するとき、Kotlinではslice()substring()を使うかと思います。
特に文字列の先頭や末尾からn文字を抽出することはよくあると思いますが、そのときにtake()takeLast()というメソッドを使うと便利でした。

使い方は以下のように至ってシンプルです。

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.
15
6
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
15
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?