Convert String to int array in java
String arr = "[1,2]";
String[] items = arr.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s", "").split(",");
int[] results = new int[items.length];
for (int i = 0; i < items.length; i++) {
try {
results[i] = Integer.parseInt(items[i]);
} catch (NumberFormatException nfe) {
//NOTE: write something here if you need to recover from formatting errors
};
}
Using Java 8's stream library, we can make this a one-liner (albeit a long line):
String str = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]";
int[] arr = Arrays.stream(str.substring(1, str.length()-1).split(","))
.map(String::trim).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(arr));
substring
removes the brackets, split
separates the array elements, trim
removes any whitespace around the number, parseInt
parses each number, and we dump the result in an array. I've included trim
to make this the inverse of Arrays.toString(int[])
, but this will also parse strings without whitespace, as in the question. If you only needed to parse strings from Arrays.toString
, you could omit trim
and use split(", ")
(note the space).
final String[] strings = {"1", "2"};
final int[] ints = new int[strings.length];
for (int i=0; i < strings.length; i++) {
ints[i] = Integer.parseInt(strings[i]);
}
It looks like JSON - it might be overkill, depending on the situation, but you could consider using a JSON library (e.g. http://json.org/java/) to parse it:
String arr = "[1,2]";
JSONArray jsonArray = (JSONArray) new JSONObject(new JSONTokener("{data:"+arr+"}")).get("data");
int[] outArr = new int[jsonArray.length()];
for(int i=0; i<jsonArray.length(); i++) {
outArr[i] = jsonArray.getInt(i);
}