I came across an unexpected feature of the split function for String in Java, here is my code:
final String line = "####";
final String[] lineData = line.split("#");
System.out.println("data: " + lineData[0] + " -- " + lineData[1]);
This code gives me an ArrayIndexOutOfBoundsException, whereas I expect it to print "and" "(two empty lines) or it can be null and null (two zero lines).
If I change my code to
final String line = " # # # #";
final String[] lineData = line.split("#");
System.out.println("data: " + lineData[0] + " -- " + lineData[1]);
Then it prints "and" "(expected behavior).
How can I make the first code without throwing an exception and giving me an array of empty strings?
thank
source
share