Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

java - Split string displays more character

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...