Java empty String split ArrayIndexOutOfBoundsException

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

+4
source share
3 answers

To achieve this, you can use the limit attribute for the split method. 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]);
+8
source

, Javadoc

, . , .

, , ArrayOutOfBoundException.

+1

If I understand your question, this will do it -

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

The problem is that the empty string is not a character.

0
source

Source: https://habr.com/ru/post/1547381/


All Articles