LoginSignup
0
0

More than 5 years have passed since last update.

Caution Java String#split

Posted at

渡されたデータによっては期待する配列を返してくれないというお話。

split.java
String str = ",,,";
String[] arrays = str.split(",")
# arrays => []
# arrays.length => 0

このように、例えば、「,,,」というデータを受け取ると長さ0の配列を返す。
これをカンマで区切られた空文字もデータとして扱いたい場合は次のように書く。
String#split(String regex, int limit) とlimit引数のあるAPIを利用する。

split.java
String str = ",,,";
String[] arrays = str.split(",", -1)
# arrays => ["", "", "", "", ""]
# arrays.length => 4

これはlimitに負の値を渡すことで配列の長さが制限されないようになるため、空文字もデータと見なして配列を返してくれるようになる。

0
0
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
0
0