h1

Extracting Integers from Strings

October 7, 2008

The following snippet of source code extracts a single digit from a String and converts it to an int. The String.charAt() method takes a zero-based index of the position of the character to be extracted from the String and the Character.digit() method takes the String from which to extract the digit and the radix.

In the example below I pass 0 to the charAt() method since I want the first character extracted and I pass 10 as the radix since I’m working in base 10.


String myString = "3blindmice";
int digit = Character.digit(myString.charAt(0), 10);
System.out.println("Digit: " + digit);

Output: 3

If the position passed to charAt is not a valid position within the String then a java.lang.StringIndexOutOfBoundsException is thrown.

If the radix is not between Character.MIN_RADIX and Character.MAX_RADIX, -1 is returned.

Comments, alternate solutions and related snippets of code are welcome.

Joshua Smith


References:

API for java.lang.Character.digit(char, int)

API for java.lang.String.charAt(int)

Advertisement

One comment

  1. That’s cool. Was not aware of this Character.digit() method so far. Thanks dude!

    Yours seems to be a nice blog. shall surf later!

    Keep up the good work!

    Cheers,



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: