Rob Avery IV Rob Avery IV - 6 months ago 16
Java Question

Java: String split(): I want it to include the empty strings in the middle and at the end

I have the following String:

String str = "\nHERE\n\nTHERE\n\nEVERYWHERE\n\n";


If you just print this, it would output like this (Of course the
\n
wouldn't be "literally" printed):

\n
HERE\n
\n
THERE\n
\n
EVERYWHERE\n
\n
\n


When I call the method
split("\n")
, I want to get all the strings between the new line (
\n
) characters even the empty strings at the end.

For example, if I did this:

String strArray[] = str.split("\n");

System.out.println("strArray.length - " + strArray.length);
for(int i = 0; i < strArray.length; i++)
System.out.println("strArray[" + i + "] - \"" + strArray[i] + "\"");


I want it to print out like this (Output A):

strArray.length - 8
strArray[0] - ""
strArray[1] - "HERE"
strArray[2] - ""
strArray[3] - "THERE"
strArray[4] - ""
strArray[5] - "EVERYWHERE"
strArray[6] - ""
strArray[7] - ""


In reality, it prints like this (Output B):

strArray.length - 6
strArray[0] - ""
strArray[1] - "HERE"
strArray[2] - ""
strArray[3] - "THERE"
strArray[4] - ""
strArray[5] - "EVERYWHERE"


How do I make the
split()
method include the empty strings like in Output A? I, of course, could write a multi-line piece of code, but wanted to know, before I waste my time trying to implement that, if there was a simple method or an extra two or so lines of code to help me. Thanks!

Answer

use str.split("\n", -1) (with a negative limit argument). When split is given zero or no limit argument it discards trailing empty fields, and when it's given a positive limit argument it limits the number of fields to that number, but a negative limit means to allow any number of fields and not discard trailing empty fields. This is documented here and the behavior is taken from Perl.