Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String split(regex for non-space) in Java 7 [duplicate]

Tags:

java

regex

split

String test="I am preparing for OCPJP";
String[] tokens=test.split("\\S");
System.out.println("length:"+tokens.length);
for(String s:tokens) {
  System.out.print("["+s+"]");
}
System.out.println();

output:

length:16
[][ ][][ ][][][][][][][][][ ][][][ ]

and now I changed split(regex) to split(regex,limit)

output:

length:21
[][ ][][ ][][][][][][][][][ ][][][ ][][][][][]

could you tell me why is this result different?Thanks a lot!

like image 284
leometal Avatar asked Sep 17 '26 15:09

leometal


1 Answers

The Javadocs for the 2-arg overload of split state:

If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

The Javadocs for the 1-arg overload of split state:

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

And the 1-arg, no limit overload is equivalent to a limit of 0. With a non-zero limit, trailing empty strings are no longer discarded. Those 5 trailing empty strings that are no longer discarded correspond to the non-spaces found in "OCPJP".

like image 51
rgettman Avatar answered Sep 19 '26 06:09

rgettman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!