我有一个字符串:
String arr = "[1,2]";
ie "[1,2]"
就像一个单一的字符串。
如何在 java 中将此 arr
转换为 int 数组?
最佳答案
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
};
}
关于java - 在java中将String转换为int数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7646392/