By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,653 Members | 1,419 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,653 IT Pros & Developers. It's quick & easy.

Extract Digits from a String

P: 94
Hi, everyone. So, suppose I have a String variable called str, with the value "123". I also have an array of integers, with length 3. I am trying to put each digit in the array:

Expand|Select|Wrap|Line Numbers
  1.  
  2. public class test
  3. {
  4.     public static void main( String[] args )
  5.     {
  6.         int digits[] = new int[ 3 ];
  7.         String str = "123";
  8.  
  9.         /* 'Extract' digits: */
  10.         for ( int i = str.length() - 1 ; i >= 0 ; i-- )
  11.         {
  12.             digits[ i ] = ( int ) str.charAt( i );
  13.         }
  14.  
  15.         /* Print array: */
  16.         for ( int i = 0 ; i <= 2 ; i++ )
  17.         {
  18.             System.out.print( digits[ i ] );
  19.         }
  20.     }
  21. }
  22.  
  23.  
This isn't working, though. IfWhen I print the number, the value 495051 is displayed. What am I doing wrong?
Aug 14 '13 #1
Share this Question
Share on Google+
3 Replies


P: 94
Solved it by changing line 12 to

Expand|Select|Wrap|Line Numbers
  1. digits[ i ] = Character.getNumericValue( str.charAt( i ) );
I think I was working with the ASCII and/or Unicode representations of 1, 2 and 3 instead.
Aug 14 '13 #2

Nepomuk
Expert 2.5K+
P: 3,112
Great work! Also, thanks for sharing your solution. :-)
Aug 16 '13 #3

P: 94
Thanks! You're welcome!
Aug 16 '13 #4

Post your reply

Sign in to post your reply or Sign up for a free account.