LoginSignup
3
2

More than 3 years have passed since last update.

KotlinでもPythonみたいに文字列操作したい!

Last updated at Posted at 2020-03-15

kotlinの文字列操作も便利だけどやっぱりPythonみたいに文字列操作したいなぁ

というわけで、kotlinでもPythonと同等の文字列操作ができるようになるライブラリを作りました。

ktPyString

Stringに対して拡張関数を定義することで、kotlinでもpythonみたいな文字列操作ができるようにしています。

導入

Gradle

build.gradle
dependencies {
    ...
    implementation 'dev.tsune:ktPyString:0.0.0'
    ...

}

Maven

<dependency>
  <groupId>dev.tsune</groupId>
  <artifactId>ktPyString</artifactId>
  <version>0.0.0</version>
  <type>pom</type>
</dependency>

依存ライブラリに追加します。

文字列操作

スライス

val str = "0123456789"
str[0,5]
// 01234
str[0,8,2]
// 0246
str[null,null,-1]
// 9876543210

Pythonista御用達のスライス操作です。

一度慣れると他の言語でもやりたくなるやつです。

ちなみに同じ動作をPythonで書くと以下のようになります。

str = "0123456789"
str[0:5]
# 01234
str[0:8:2]
# 0246
str[::-1]
# 9876543210

文字列検索

// 先頭からの検索  
"123412312312345".find("123") // 0

// 開始位置を指定して検索
"123412312312345".find("123",start:2) // 4

// 終了位置を指定して検索
"123412312312345".find("123",end:1) // -1

// 末尾からの検索
"123412312312345".rfind("123") // 10

末尾からの検索も同様に開始位置と終了位置を指定して検索できます。

文字列結合

val array = ["abc","def","ghi"]
"".join(array) // "abcdefghi"
"-".join(array) // "abc-def-ghi"
"++".join(array) // "abc++def++ghi"

文字列分割

行ごとの分割
"abc\nabc".splitlines() // ["abc", "abc"]
"abc\r\nabc\n".splitlines() // ["abc", "abc"]

// 改行文字を残して分割
"abc\nabc\r".splitlines(true) // ["abc\n", "abc\r"]
"abc\r\nabc\n".splitlines(true) // ["abc\r\n", "abc\n"]

トリミング

// 右端のみ
"rstrip sample   ".rstrip() // "rstrip sample"
"rstrip sample   ".rstrip("sample ") // "rstri"
"  rstrip sample".rstrip() // "  rstrip sample"

// 左端のみ
"  lstrip sample".lstrip() // "lstrip sample"
"  lstrip sample".lstrip(" ls") // "trip sample"
"lstrip sample".lstrip() // "lstrip sample"

// 両端
"   spacious   ".strip() // "spacious"
"www.example.com".strip("cmowz.") // "example"

出現回数カウント

"abc abc abc".count("abc") // 3

// 開始位置の指定
"abc abc abc".count("abc", start:2) // 2

// 終了位置の指定
"abc abc abc".count("abc", end:1) // 0

ゼロ埋め

"abc".zfill(1) // "abc"
"abc".zfill(5) // "00abc"

// 符号付きの場合
"+12".zfill(5) // "+0012"
"-3".zfill(5) // "-0003"
"+12".zfill(2) // "+12"

符号付きの場合は符号の後ろにゼロが入ります。

さいごに

全部書いていると長くなってしまうので、紹介はこの辺りで。

このほかにも、Pythonのstr型で利用できるメソッドは言語機能的に実現不可能または、実現が難しいもの以外ほとんどサポートしています。

Pythonからプログラミングを始めたという人なら、慣れ親しんだPythonの文字列操作ができるようになるので比較的便利ではないでしょうか?

このメソッド実装できるよ、とかこっちの実装の方がパフォーマンスいいんじゃない?

kotlinだったらこう書くと綺麗だよ等ありましたら教えてください。

プルリクお待ちしております。

もしあれば、バグ報告とかも嬉しいです。

余談ですが、Swift版のライブラリも過去に作っているので、iOSとAndroidで文字列操作周りの処理をほとんどコピペで動かすこともできるかも知れません。(Swiftとkotlin の文法が割と似ているので)
https://qiita.com/ChanTsune/items/bd611a4c778c0fb338e6

3
2
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
3
2