0

Write a function which takes a number represented as a String as an argument, for example "12345" or "4321432143214321" and returns the digits of that number in an array.

Your function should create an int[] array with one digit of your number per element.

Can someone please a hint as how I can approach this problem?

3
  • second answer stackoverflow.com/questions/8391979/… Commented Feb 3, 2016 at 1:44
  • @capslock And the array is where? Commented Feb 3, 2016 at 1:46
  • my bad I read too fast Commented Feb 3, 2016 at 1:48

3 Answers 3

1
public int[] convertToArray(String str){
    int array[] = new int[str.length()];
    for(int i = 0; i < array.length; i++){
       try{
           array[i] = Integer.parseInt(str.substring(i,i+1));
       }catch(NumberFormatException e){
           e.printStackTrace();
           array[i] = 0;
       }
    }
    return array;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Just for fun, a Java 8 solution:

int[] result = input.codePoints().map(Character::getNumericValue).toArray();

Comments

0
int[] getStringAsArray(String input) {
    int[] result = new int[input.length()];

    for (int i=0; i < input.length(); ++i) {
        result[i] = Character.getNumericValue(input.charAt(i));
    }

    return result;
}

Note that any character in the input string which is not a number will be converted to a negative value in the output int[] array, so your calling code should check for this.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.