size of the array is returned "10", whereas it should have been 9. Anyway if we say it is because of blank string "", then it should be 11; staring and ending!!! What is the matter here?
Please help!
Thanks, cmbhatt [ April 24, 2007: Message edited by: Barry Gaunt ]
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.
Never ascribe to malice that which can be adequately explained by stupidity.
m ali
Ranch Hand
Joined: Apr 12, 2007
Posts: 49
posted
0
hey its count is 10, including the starting and ending... doesn't it?
Thanks.
Chandra Bhatt
Ranch Hand
Joined: Feb 28, 2007
Posts: 1707
posted
0
Well Fred,
It means, if we don't pass the second argument (limit), 0 is used internally.
It should result 11 but doesn't give.
Why length+2 gives 11 (as exptected)
What does split() does if limit is negative?
Thanks, cmbhatt
Meena R. Krishnan
Ranch Hand
Joined: Aug 13, 2006
Posts: 178
posted
0
..checking the API and this is what I found: 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.
This is all documented in the JavaDocs for the split() method.
[Quote deleted -- as already quoted]
In fact, the JavaDoc even follows this up with plenty of examples...
As a side note, I am generally one of those people who never get burned by something more than once (ie. I always learn from my mistakes). One of the few exceptions is the split() method. For some reason, I keep forgetting that the split() method, by default, will truncate trailing zero length matches.
Henry [ April 24, 2007: Message edited by: Henry Wong ]
Yes, by space I meant a blank space. See the o/p posted following that.
The eg. is mainly to see how it works as per the API doc.
When the limit is a non-positive number, the pattern is searched-for repeatedly until the end of the string and it returns the trailing spaces, if any. In the eg. string "abcdabcdabcdaa", the last two 'a's return empty strings. o/p:
Also, in this case, no matter what the number is -1 or -10 or whatever, the result is the same. Why? I'm not sure.
Zero or no limit split: In the case of a split with no limit or with zero limit, the last two 'a's were not returned, thereby as per the API, the trailing spaces were not returned.
Why it is behaving differently? that's a question for the java experts.