Line Split Behavior

I do not understand why the following conclusion makes sense.

A method for breaking strings on an empty string that returns an array of a string with a length of 1

String[] split = "".split(",");
System.out.println(split.length);
Returns a String array of length 1

String[] split = "Java".split(",");
System.out.println(split.length);
Returns a String array of length 1

How to differentiate?

+5
source share
4 answers

From the documentation :

The array returned by this method contains each substring of this string that ends with another substring that matches the given expression or ends at the end of the string.

To answer your question, it does what is expected: the returned substring ends at the end of the input line (since there was no one found ,). The documentation also states:

- , , .

, . , Java , .

+10

. , , , . , StringTokenizer:

StringTokenizer st = new StringTokenizer(someString,',');
int numberOfSubstrings = st.countTokens();
+2

It returns the original string (which in this case is an empty string) since it was not there to split.

+1
source

It returns one, because you are measuring the size of a split array that contains one element: an empty string.

0
source

All Articles