Hello All,
I am trying to split a String object below -:
String price = "150.0"
String priceArr[] = price.split(".", 2);
String dollars = priceArr[0];
String cents = priceArr[1];
Why is it that 'dollars' is assigned "" and 'cents' is assigned
"50.0"? I would like 'dollars' to be assigned "150" and 'cents' to be
assigned "0". What am I doing wrong here? I appreciate any effort to
help me. Thank you for your time and consideration.
Sincerely,
Sisilla
Sisilla - 11 Mar 2008 18:52 GMT
Here is the solution if anyone is curious:
The period/dot is a special character in Regular Expressions and has
the meaning "any character". If you want to split around the dot, you
need to use the expression "/."
Sisilla - 11 Mar 2008 18:55 GMT
Oops. That should be "\."
> The period/dot is a special character in Regular Expressions and has
> the meaning "any character". If you want to split around the dot, you
> need to use the expression "/."
Sisilla - 11 Mar 2008 18:59 GMT
Actually you need "\\."
By escaping the dot a reference to the dot is created, as opposed to
the 'any character' meaning; the backslask then needs to be repeated
because Java will strip a backslash before passing the expression to
the Regex engine.
Roedy Green - 12 Mar 2008 01:59 GMT
On Tue, 11 Mar 2008 10:46:44 -0700 (PDT), Sisilla
<sisilla14@gmail.com> wrote, quoted or indirectly quoted someone who
said :
>String priceArr[] = price.split(".", 2);
you mean literal ., . is a magic regex command meaning any char.
You must "quote" it. See http://mindprod.com/jgloss/regex.html
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com