Re: Convert a String to Int: can I use toInt() instead of Integer.parseInt()?
On 7/6/2011 3:36 PM, markspace wrote:
On 7/6/2011 2:58 PM, Thee Chicago Wolf [MVP] wrote:
Well, I originally used int[] x = new int[str.length]; but it gives a
compile error. (str.length()] does work though. Guessing because it's
Yup, I missed that one, it's length().
stuff that I used. Thanks for that tip! But does the - '0' portion of
x[i] = str.charAt(i) - '0'; just tell it to convert to its ASCII
value? We dicussed this here and were like WTF is this? What exactly
is that portion doing? Thanks for walking me through it.
For ASCII values, UTF (what Java uses) and ASCII are the same values.
"char" is an integer already, there's no need to convert. str.charAt( x
) already returns a number, just a number encoded to mean a UTF
character (code point?).
So, you just have to map one number range to another. '0' is 48 decimal.
E.g.:
'0' - '0' = 48 - 48 = 0.
'1' - '0' = 49 - 48 = 1.
'2' - '0' = 50 - 48 = 2.
etc. Remember Neo in The Matrix? It's all just number, really, even the
letters.
Or, of course, you could use the Character.digit method. It's a bit more
flexible, allowing a one line change e.g. to do hexadecimal instead of
decimal, and providing easy internationalization.
I realize these issues will probably not arise in this context, but in
general it is better to learn to use API methods than to roll your own
that deals with a subset of the cases.
Patricia