How to split the string with slash correctly

  • A+


String line = "/abc/1/"; String[] tokens = line.split("/"); 

I want to get {"", "abc", "1", ""}.

However, the actual output is {"", "abc", "1"}.

What confuses me is why there is only one "", maybe there is something wrong with line.split("/").


Use the not-often-used second parameter of String#split:

String line = "/abc/1/"; String[] tokens = line.split("/", -1); 

This returns {"", "abc", "1", ""}.


From the documentation for String#split(String pattern, int n):

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: