I can’t get these examples from the SUN tutorial of String split:
E.g. for "boo:and:foo"
Regex Limit Result
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" }
I can’t understand the result.
I read that for negative limit the pattern is applied as many times as possible and for positive limit it is applied n-1 times etc.
But I can’t understand how the resulting array is formed in each case.
E.g. in first case why we have 1 “” in location 1 but 2 “” in locations 3 and 4?
Same for the rest.
Any help?
Let’s start by understanding all possible splits. I think
"b"and":and:f"are clear.The empty strings came from splitting between
o‘s (fo-""-o,bo-""-o), and splitting after the last o – until the end of the string, which is again – an empty strng.So totally we have 5 matching strings that the split can return.
If we split using 5 – we return at most 5 substrings, whcih is exactly the 5 substrings we have, resulting in the first output:
If we split using -2, we return as much as possible [which is identical to 5 in this case]:
If we split using 0, we return as much as possible – but we discard al the trailing empty strings:
Note: If you want to ignore the empty strings between occurances of
o, you should split with the regex"o+"– which takes as mucho‘s as possible, thus resulting in no empty strings from betweeno‘s