Bing Zhao :
Code:
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("/")
.
Tim Biegeleisen :
Use the not-often-used second parameter of String#split
:
String line = "/abc/1/";
String[] tokens = line.split("/", -1);
This returns {"", "abc", "1", ""}
.
Demo
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