Extracting Integers from Strings

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.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s