String split not returning empty results

split does include empty matches in the result, have a look at the docs here. However, by default, trailing empty strings (those at the end of the array) are discarded. If you want to include these as well, try split(":", -1).


Works for me.

class t {
    public static void main(String[] _) {
        String t1 = "value1:value2::value3";
        String[] t2 = t1.split(":");
        System.out.println("t2 has "+t2.length+" elements");
        for (String tt : t2) System.out.println("\""+tt+"\"");
    }
}

gives the output

$ java t
t2 has 4 elements
"value1"
"value2"
""
"value3"

I think that a StringTokenizer might work better for you, YMMV.


I don't honestly see the big draw of split. StringTokenizer works just as well for most things like this and will easily send back the tokens (so you can tell there was nothing in between :: ).

I just wish it worked a little better with the enhanced for loop, but that aside, it wouldn't hurt to give it a try.

I think there is a regexp trick to get your matched tokens to return as well but I've gone 20 years without learning regexp and it's still never been the best answer to any problem I've tackled (Not that I would actually know since I don't ever use it, but the non-regexp solutions are generally too easy to beat.)