• Post Reply Bookmark Topic Watch Topic
  • New Topic

problem with String.split()  RSS feed

 
Pin Ting
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, All Ranchers:

I've a problem with String.split(), and I summarized as the following code piece:

the output on console is:

segment[0] = ""
segment[1] = "-3.45"
segment[2] = "6.38"


but what I expected is:

segment[0] = "-3.45"
segment[1] = "6.38"


any hint is deeply appreciated.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving this to the Intermediate forum...
 
Luke Knightley
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try:
 
Pin Ting
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Luke's work around really works.

In light of Luke's code, we can also write this way:

or this way:


But I am still wondering why there is an empty string in the return array of String.split():


It seems that if there is a matched pattern in the beginning of the input string, the return array of String.split() would have an empty string indexed 0. Why

Thanks in advance.
 
Alan Moore
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose you have some simple CSV data in which some of the fields may be empty. Split() has to return a value for each field in order to keep in synch with the data, so it returns an empty string for each empty field. It would be an error for it to ignore the first field because it happened to be empty. Whether or not to ignore leading empty fields was an arbitrary choice, which happens to be incorrect for your situation, but is correct more often than not. In fact, split() does ignore trailing empty fields by default, which would be incorrect for the CSV data, but works for you.

BTW, your alternate approaches don't look like they would work. What Luke did was to strip off the parentheses (and anything outside them), then split on the sequence 'comma-space'. But you're removing all parentheses, commas and spaces, then trying to split on those same characters. I think you meant to do this:...or this:Notice that there's no '^' in either of those patterns; I'm not sure what you were trying to do with that, but it didn't belong there.
 
Pin Ting
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to Alan, whose remark really enlightened me.

"^" in regex means "The beginning of a line".
web page
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!