Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not sure how string split actually works in this case

I don't get the following:

In the following String:

String s = "1234;x;;y;";

if I do:
String[] s2 = s.split(";");

I get s2.length to be 4 and

s2[0] = "1234";  
s2[1] = "x";  
s2[2] = "";  
s2[3] = "y"; 

But in the string: String s = "1234;x;y;;";

I get:

s2.length to be 3 and

s2[0] = "1234";  
s2[1] = "x";  
s2[2] = "y"; 

?

What is the difference and I don't get 4 in the latter case as well?

UPDATE:
Using -1 is not was I was expecting as behavior.
I mean the last semicolon is the end of the String so in the latter example I was also expecting 4 as length of the array

like image 993
Jim Avatar asked Feb 15 '12 09:02

Jim


People also ask

How does string split work?

The string split() method breaks a given string around matches of the given regular expression. After splitting against the given regular expression, this method returns a string array.

How do you split a string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How split method works in Python?

The split() function works by scanning the given string or line based on the separator passed as the parameter to the split() function. In case the separator is not passed as a parameter to the split() function, the white spaces in the given string or line are considered as the separator by the split() function.


1 Answers

From the docs,

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.

UPDATE:

You have five substrings separated by ; In the second case, these are 1234, x, y, and . As per the docs, all empty substrings (at the end) which result from the split operation would be eliminated. For details, look here.

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.

The string boo:and:foo, for example, yields the following results with these parameters:

Regex   Limit   Result
  :       2     { "boo", "and:foo" }
  :       5     { "boo", "and", "foo" }
  :      -2     { "boo", "and", "foo" }
  o       5     { "b", "", ":and:f", "", "" }
  o      -2     { "b", "", ":and:f", "", "" }
  o       0     { "b", "", ":and:f" }   // all the empty substrings at the end were eliminated
like image 183
Pulkit Goyal Avatar answered Oct 19 '22 03:10

Pulkit Goyal