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?

hotzst
  • 6,834
  • 8
  • 36
  • 59
Intelligent
  • 117
  • 1
  • 10

3 Answers3

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;
}
user3501676
  • 387
  • 1
  • 2
  • 8
1

Just for fun, a Java 8 solution:

int[] result = input.codePoints().map(Character::getNumericValue).toArray();
Robert Bräutigam
  • 7,163
  • 1
  • 18
  • 36
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.

Tim Biegeleisen
  • 451,927
  • 24
  • 239
  • 318