Example of the split method using the limit parameter

To understand the impact of the limit parameter, let's take a comma-separated input string with two trailing commas:

fox,tiger,wolf,, 

We can call the split method in two ways. We can call the split method with limit=0:

String[] arr = input.split(",", 0); 

We can also call the single parameter split method call as:

String[] arr = input.split(","); 

It splits the input string around a comma and the trailing empty strings are discarded, with the following values being returned by the split method:

"fox" 
"tiger"
"wolf"

Now, let's call the split method with limit=1:

String[] arr = input.split(",", 1); 

It splits the input string around a comma and then gets a single element in the resulting array, that is, the input string itself. The following value is returned by the split method:

"fox,tiger,wolf,," 

Let's call the split method with limit=2:

String[] arr = input.split(",", 2); 

It splits the input string around a comma and then gets exactly two elements in the resulting array. The following two values are returned by the split method:

"fox" 
"tiger,wolf,,"

Let's call the split method with limit=3:

String[] arr = input.split(",", 3); 

It splits the input string around a comma, and then we get exactly three elements in the resulting array. The following three values are returned by the split method:

"fox" 
"tiger"
"wolf,,"

Let's call the split method with a negative limit:

String[] arr = input.split(",", -1); 

It splits the input string around a comma as many times as possible, with the trailing empty strings included in the split array, and we get these elements in the resulting array. The following values are returned by the split method. Note the two empty strings at the end of the split array:

"fox" 
"tiger"
"wolf"
""
""
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.186.109