Extract Digits from a String

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • stdq
    New Member
    • Apr 2013
    • 94

    Extract Digits from a String

    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:

    Code:
    public class test
    {
        public static void main( String[] args )
        {
            int digits[] = new int[ 3 ];
            String str = "123";
            
            /* 'Extract' digits: */
            for ( int i = str.length() - 1 ; i >= 0 ; i-- )
            {
                digits[ i ] = ( int ) str.charAt( i );
            }
            
            /* Print array: */
            for ( int i = 0 ; i <= 2 ; i++ )
            {
                System.out.print( digits[ i ] );
            }
        }
    }
    This isn't working, though. IfWhen I print the number, the value 495051 is displayed. What am I doing wrong?
  • stdq
    New Member
    • Apr 2013
    • 94

    #2
    Solved it by changing line 12 to

    Code:
    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.

    Comment

    • Nepomuk
      Recognized Expert Specialist
      • Aug 2007
      • 3111

      #3
      Great work! Also, thanks for sharing your solution. :-)

      Comment

      • stdq
        New Member
        • Apr 2013
        • 94

        #4
        Thanks! You're welcome!

        Comment

        Working...