1

I'm using Android Studio and I have this String in one of my activities:

[0, 25, 24, 25, 15, 16, 17, 25, 24, 21, 24]

and I want to convert it to a int[] :

{0, 25, 24, 25, 15, 16, 17, 25, 24, 21, 24};

How do I do that? I tried the code below, but it's not returning the correct value.

int[] intArray = new int[string.length()];

for (int i = 0; i < string.length(); i++) {
    intArray[i] = Character.digit(string.charAt(i), 10);
}
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
João Amaro
  • 454
  • 2
  • 10
  • 23

3 Answers3

2

This is called "parsing". You will need to solve this with your own code. There is no built-in method in Java or Android to do so. You should look at the methods available in the String class, especially matches() and split().

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
1

On Android, you can make use of org.json.JSONArray:

JSONArray jsonArray = new JSONArray(arr); // throws JSONException
int length = jsonArray.length();
int[] results = new int[length];

for (int i = 0; i < length; ++i) {
  results[i] = jsonArray.get(i);
}
Alexander Pavlov
  • 31,598
  • 5
  • 67
  • 93
1
String[] arr = [...];
int[] ints = new int[arr.length()];
for(int i = 0 ; i < arr.length() ; i++){
    ints[i] = Integer.parseInt(arr[i]);
}
Salman Tariq
  • 353
  • 1
  • 11