Frederik Witte
Frederik Witte

Reputation: 1345

Java difference between "split(regEx)" and "split(regEx, 0)"?

Is there any difference between using split(regEx) and split(regEx, 0)?

Because the output is for the cases I tested the same. Ex:

String myS = this is stack overflow;
String[] mySA = myS.split(' ');

results in mySA === {'this','is','stack,'overflow'}

And

String myS = this is stack overflow;
String[] mySA = myS.split(' ', 0);

also results in mySA === {'this','is','stack,'overflow'}

Is there something "hidden" going on here? Or something else which needs to be known about the .split(regEx, 0)?

Upvotes: 1

Views: 72

Answers (2)

Rajesh
Rajesh

Reputation: 384

Answering the question. Yes they're same.

Please find the split method of String class which intern calls the split(regex,0) method.

public String[] split(String regex) {
    return split(regex, 0);
}

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. 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

For example the following code can give you some insight.

String myS = "this is stack overflow";
String[] mySA = myS.split(" ", 2);
String[] withOutLimit = myS.split(" "); 
System.out.println(mySA.length); // prints 2
System.out.println(withOutLimit.length); // prints 4

Upvotes: 0

nhahtdh
nhahtdh

Reputation: 56819

They are essentially the same.

Quoted from String.split(String regex) documentation:

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.

Upvotes: 5

Related Questions