将包含整数数组的字符串转换为整数数组in java
问题描述:
我从前端发送JSON
并在JAVA(后端)中读取它,其中变量abc包含整数列表。将包含整数数组的字符串转换为整数数组in java
我有一个String locationjson = "["12","55","62","90"]";
我想将其转换为Arraylist/List<Integer>
在java中...我已经搜查了计算器的答案,但它是在Javascript的情况下解决了,我想在Java解决方案。
答
String abc = "[\"12\",\"55\",\"62\",\"90\"]";
String[] stringArray = abc.substring(1, abc.length() - 1).split(",");
List<Integer> integerList = new ArrayList<>();
for (String s: stringArray) {
integerList.add(Integer.parseInt(s.substring(1, s.length() - 1)));
}
答
您可以使用正则表达式来找到这个字符串的INT所以你可以使用这个:
public static void main(String[] args) {
String str = "\"[\"12\",\"55\",\"62\",\"90\"]\"";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(str);
List<Integer> list = new ArrayList<>();
while (m.find()) {
list.add(Integer.parseInt(m.group()));
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
希望这可以帮助你。
+0
精湛...非常非常感谢的人......它的工作...... –
+0
欢迎你@VaibhavShimpi –
parseInt不会做你?? – apomene
为什么不使用JSON库来解析它,然后在每个字符串上使用'parseInt'? – bfontaine
这是String对象 - >'String locationjson =“[”12“,”55“,”62“,”90“]”;'? –