Java: String split(): I want it to include the empty strings at the end
JavaStringSplitJava 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)));