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

I have the following line:

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

If you just type this, it will be output as follows (of course, \n will not be "literally" printed):

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

When I call the split("\n") method split("\n") , I want all lines between newlines ( \n ) to even empty lines 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 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] - "" 

It is currently printed as follows (output B), and any trailing blank lines 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 blank lines, as in Output A? Of course, I could write a multi-line code fragment, but I wanted to know before I wasted time on its implementation if there was a simple way or two additional lines of code that could help me. Thank!

+43
java string split
Dec 18 '12 at 19:01
source share
3 answers

use str.split("\n", -1) (with a negative argument to limit ). When split set to zero or not the limit argument, it discards the final empty fields, and when it is assigned a positive limit argument, it limits the number of fields to this number, but a negative limit means allow any number of fields and not discard the final empty fields. This is described here and the behavior is taken from Perl.

+96
Dec 18 '12 at 19:16
source share

The single argument split method is specified to ignore the final empty line separators, but the version that accepts the "limit" argument saves them, so one option would be to use this version with a large limit.

 String strArray[] = str.split("\n", Integer.MAX_VALUE); 
+6
Dec 18 '12 at 19:11
source share

Personally, I like the Guava splitting utility:

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

Then, if you want to customize the behavior of the empty string, you can do this:

 System.out.println(Iterables.toString( Splitter.on('\n').omitEmptyStrings().split(input))); 
+2
Dec 18 '12 at 19:18
source share



All Articles