Invertir (analizar la salida) de Arrays.toString (int []) [duplicar]
-
19-08-2019 - |
Pregunta
Esta pregunta ya tiene una respuesta aquí:
- Convierta String a una matriz int en java 9 respuestas
¿Existe en el JDK o Jakarta Commons (o en cualquier otro lugar) un método que pueda analizar la salida de Arrays.toString, al menos para las matrices de enteros?
int[] i = fromString(Arrays.toString(new int[] { 1, 2, 3} );
Solución
Es bastante fácil hacerlo usted mismo:
public class Test {
public static void main(String args[]){
int[] i = fromString(Arrays.toString(new int[] { 1, 2, 3} ));
}
private static int[] fromString(String string) {
String[] strings = string.replace("[", "").replace("]", "").split(", ");
int result[] = new int[strings.length];
for (int i = 0; i < result.length; i++) {
result[i] = Integer.parseInt(strings[i]);
}
return result;
}
}
Otros consejos
Una muestra con fastjson, una biblioteca JSON:
String s = Arrays.toString(new int[] { 1, 2, 3 });
Integer[] result = ((JSONArray) JSONArray.parse(s)).toArray(new Integer[] {});
Otra muestra con guayaba:
String s = Arrays.toString(new int[] { 1, 2, 3 });
Iterable<String> i = Splitter.on(",")
.trimResults(CharMatcher.WHITESPACE.or(CharMatcher.anyOf("[]"))).split(s);
Integer[] result = FluentIterable.from(i).transform(Ints.stringConverter())
.toArray(Integer.class);
También puede usar split / join desde Apache Commons ' StringUtils
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow