LoginSignup
9
5

More than 3 years have passed since last update.

Kotlinで文字列の先頭・末尾から指定した文字列を削除する

Last updated at Posted at 2019-07-29

文字列の先頭から指定した文字列を削除する

例えば、「Documents/hogehoge」という文字列から「hogehoge」を取り出したいときは、Stringクラスの拡張関数removePrefixメソッドを使います。
このメソッドは文字列の先頭から指定した文字列を削除します。

prefix.kt
val str = "Documents/hogehoge"
val newStr = str.removePrefix("Documents/") // "hogehoge"

これで「hogehoge」が取り出せます。

文字列の末尾から指定した文字列を削除する

例えば、「hogehoge.csv」という文字列から拡張子を取り除いた「hogehoge」を取り出したいときは、Stringクラスの拡張関数removeSuffixメソッドを使います。
このメソッドは文字列の末尾から指定した文字列を削除します。

suffix.kt
val str = "hogehoge.csv"
val newStr = str.removeSuffix(".csv") // "hogehoge"

これで「hogehoge」が取り出せます。

参考

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/remove-prefix.html
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/remove-suffix.html

9
5
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
9
5