Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.programmer > #38499
| From | Andreas Leitgeb <avl@logic.at> |
|---|---|
| Newsgroups | comp.lang.java.programmer |
| Subject | "less for more" - a little story about String.split |
| Date | 2018-07-27 06:33 +0000 |
| Organization | A noiseless patient Spider |
| Message-ID | <slrnpllf5d.e93.avl@logic.at> (permalink) |
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?
Back to comp.lang.java.programmer | Previous | Next — Next in thread | Find similar | Unroll thread
"less for more" - a little story about String.split Andreas Leitgeb <avl@logic.at> - 2018-07-27 06:33 +0000
Re: "less for more" - a little story about String.split nobody@example.org (Scott) - 2018-07-28 01:16 +0000
Re: "less for more" - a little story about String.split Andreas Leitgeb <avl@logic.at> - 2018-07-28 13:04 +0000
csiph-web