106

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!

1
  • 1
    @Tom good point, I was confused since I was getting only empty strings in my case (which, in reality meant, "only trailing empty strings") I've attempted to clarify now, thanks! Commented May 26, 2016 at 22:52

3 Answers 3

205

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.

Sign up to request clarification or add additional context in comments.

Comments

9

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);

3 Comments

Do you know the syntax to do this?
using negative limit is better than using max int imho
3

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))); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.