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
  • 954,112
  • 185
  • 2,315
  • 2,367
João Amaro
  • 390
  • 1
  • 5
  • 21

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
  • 76,639
  • 19
  • 130
  • 241
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
  • 30,691
  • 5
  • 65
  • 91
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