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