Path: csiph.com!xmission!nnrp.xmission!.POSTED.skb.dsl.xmission.com!not-for-mail From: nobody@example.org (Scott) Newsgroups: comp.lang.java.programmer Subject: Re: "less for more" - a little story about String.split Date: Sat, 28 Jul 2018 01:16:46 GMT Organization: XMission http://xmission.com/ Message-ID: <5b5bbee9.431171906@news.xmission.com> References: Injection-Info: news.xmission.com; posting-host="skb.dsl.xmission.com:166.70.236.23"; logging-data="24466"; mail-complaints-to="abuse@xmission.com" X-Newsreader: Forte Free Agent 1.21/32.243 Xref: csiph.com comp.lang.java.programmer:38506 On Fri, 27 Jul 2018 06:33:17 -0000 (UTC), Andreas Leitgeb wrote: >Imagine you have a variable named "text" of type String, and then you >have this line of code: > String lines[] = text.split( "\n" ); > >If text originally pointed to an empty string, then you get an array >of length 1, holding an empty string. > >If, however, you append a certain char to that string, then you may >end up with a zero-length array returned from split! Namely, if ... >(*** drum roll ***) >...the char you added matches split's delimiter: text.equals("\n"). > >The javadoc of String.split gives these clues about array length in >the case of a 0 limit: > >We have clue #1a: >" The array returned by this method contains each substring of this >" string that is terminated by another substring that matches the given >" expression *or is terminated by the end of the string*. [my emphasis] >[this essentially describes the effect of split with a negative limit] > >We have clue #1b: >" If the expression does not match any part of the input then the >" resulting array has just one element, namely this string. >[This is just a corollary of #1a for the case of no matches.] > >and we have clue #2: >" 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*. [again my emphasis] > >Which overrides #1a but not #1b. > >Could anyone explain to me, why emphasiszed part of clue #2 only >applies to a String that contains at least one delimiter? Why is >clue #2 weaker than clue #1b but stronger than clue #1a ? > >Who else ever had a bug from wrongly assuming that split would >always return an array of length at least 1, or maybe the other >way: expecting 0-length arrays for splitting the empty string >with a limit 0? A cursory reading of the spec suggests that split can indeed return zero strings when limit=0. "...and trailing empty strings will be discarded", it says it right there. If the result contains nothing *but* empty strings, why would you expect any different? It looks like you get to keep all substrings, even empty ones, by setting limit!=0. The implied exception seems to be that the above does not apply to a string that contains no matching delimiters, which is simply returned as-is, even if it's empty. But I'm new to Java, maybe I'm reading the spec wrong.