Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to split a string which is 17 bytes but when I display the length it displays 18.

String s1 = "{{ (( 4 + 5 )) }}";
String[] s2 = s1.split("");
System.out.println("length = " + s2.length);

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
196 views
Welcome To Ask or Share your Answers For Others

1 Answer

It shows a length of 18 in Java 7 because splitting by an empty string will find a delimiter before and after every character.

 { {   ( (...
^ ^ ^ ^ ^ 

In Java 7, trailing empty strings are discarded.

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.

So, in Java 7, I get a length of 18, because the trailing empty string is discarded, but the leading empty string is not discarded.

Including this line

System.out.println(Arrays.toString(s2));

yields this output

[, {, {,  , (, (,  , 4,  , +,  , 5,  , ), ),  , }, }]

with a leading empty string.

However, in Java 8, this statement is now included in the Javadocs.

When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array. A zero-width match at the beginning however never produces such empty leading substring.

It is not present in the Java 7 javadocs.

It looks like the behavior has been changed to eliminate leading strings for zero-width matches, which is the case for this question.

Java 8 output:

[{, {,  , (, (,  , 4,  , +,  , 5,  , ), ),  , }, }]

The beginning , after the array print of [ is now gone, and the length is now 17.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...