Java empty String split ArrayIndexOutOfBoundsException

java, split, string

Solution

You can use the limit attribute of split method to achieve this. Try

final String line = "####";
final String[] lineData = line.split("#", -1);
System.out.println("Array length : " + lineData.length);
System.out.println("data: " + lineData[0] + " -- " + lineData[1]);

Problem

I have come across an unexpected feature in the split function of 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 would expect it to print "" and "" (two empty Strings), or maybe null and null (two null Strings). If I change my code for ``` final String line = " # # # #"; final String[] lineData = line.split("#"); System.out.println("data: " + lineData[0] + " -- " + lineData[1]); ``` Then it prints " " and " " (the expected behaviour). How can I make my first code not throwing an exception, and giving me an array of empty Strings? Thanks

Original source

Related problems