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

JavaStringSplit

Java Problem Overview


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 strings between the new line (\n) characters even empty strings at the end.

For example, if I do this today:

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] - ""

Currently, it prints like this (Output B), and any ending empty strings are skipped:

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!

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

The one-argument split method is specified to ignore trailing empty string splits but the version that takes a "limit" argument preserves them, so one option would be to use that version with a large limit.

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

Solution 3 - Java

Personally, I like the Guava utility for splitting:

System.out.println(Iterables.toString(
   Splitter.on('\n').split(input)));

Then if you want to configure empty string behaviour, you can do so:

System.out.println(Iterables.toString(
   Splitter.on('\n').omitEmptyStrings().split(input))); 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRob Avery IVView Question on Stackoverflow
Solution 1 - JavahobbsView Answer on Stackoverflow
Solution 2 - JavaIan RobertsView Answer on Stackoverflow
Solution 3 - JavaMark PetersView Answer on Stackoverflow