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
  • 7,238
  • 9
  • 41
  • 64
Intelligent
  • 127
  • 1
  • 12

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
  • 437
  • 1
  • 4
  • 8
1

Just for fun, a Java 8 solution:

int[] result = input.codePoints().map(Character::getNumericValue).toArray();
Robert Bräutigam
  • 7,514
  • 1
  • 20
  • 38
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
  • 502,043
  • 27
  • 286
  • 360