Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java empty String split ArrayIndexOutOfBoundsException [duplicate]

Tags:

java

string

split

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

like image 967
toni07 Avatar asked Jan 10 '23 06:01

toni07


1 Answers

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]);
like image 116
Syam S Avatar answered Jan 22 '23 10:01

Syam S