[英]How to get number from string array in java
i have a string like String[] str = {"[5, 2, 3]","[2, 2, 3, 10, 6]"}
and i need to take numbers to add into an integer list.我有一个像
String[] str = {"[5, 2, 3]","[2, 2, 3, 10, 6]"}
这样的字符串,我需要将数字添加到 integer 列表中。
i tried to split first index into numbers to see if it will work, looks like:我试图将第一个索引拆分为数字以查看它是否有效,如下所示:
String[] par = str[0].split("[, ?.@]+");
After the split i tried to see what array i get:拆分后,我试图查看我得到的数组:
for(String a: par)
System.out.println(a);
But when i wrote that code i get an array like this:但是当我编写该代码时,我得到一个像这样的数组:
[5
2
3]
So, how can i get rid of this square brackets?那么,我怎样才能摆脱这个方括号呢?
Instead of your current pattern, I would use \\D+
which will split on one or more non-digits.我会使用
\\D+
而不是您当前的模式,它将拆分为一个或多个非数字。 Add a guard for the empty string too.也为空字符串添加保护。 Something like
就像是
String[] str = { "[5, 2, 3]", "[2, 2, 3, 10, 6]" };
for (String par : str) {
for (String t : par.split("\\D+")) {
if (t.isEmpty()) {
continue;
}
System.out.println(Integer.parseInt(t));
}
}
Outputs输出
5
2
3
2
2
3
10
6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.