java - 有没有办法从字符串遍历到 int 数组,反之亦然

标签 java arrays string

在Java中,给定数组

int a[] = {1,2,3}

我可以通过 Arrays.toString(a) 来获取

"[1,2,3]"

是否有同样方便的方法将此 String 返回到其先行数组? 或者我必须经历整个 split、for 循环、parseInt 东西吗?

更新

感谢大家的所有想法。我推出了自己的功能作为

String src[] = data.split("\\D+");//data is intArrayAsString: [1,2,3]
int[] nums = new int[src.length - 1];
int ndx = 0;
for (String s : src) {
  try {
    nums[ndx] = Integer.parseInt(s);
    ndx++;
  } catch (NumberFormatException e) {
  }
}
return nums;

注意:“遍历”这个词似乎让一些人望而却步。 “遍历”是指从字符串到 int 数组来回移动的能力。

最佳答案

据我所知,没有。

但使用 Split 很容易做到.

我刚刚做了这个,如果你不明白怎么做:

int[] arr = {1, 2, 3, 4};
String toString = Arrays.toString(arr);

System.out.println(toString);

// we know it starts with [ and ] so we skip it
String[] items = toString.substring(1, toString.length() - 1).split(",");
int[] arr2 = new int[items.length];
for (int i = 0; i < items.length; ++i)
{
    arr2[i] = Integer.parseInt(items[i].trim()); // .trim() because it adds the space and parseInt don't like spaces
}

System.out.println(Arrays.toString(arr2));

(可以自由改进,只是草稿)

关于java - 有没有办法从字符串遍历到 int 数组,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22273524/

相关文章:

java - menuBuilder.setOptionalIconsVisible 只能从同一个库组中调用

java - (IntelliJ) Maven 将 png 资源添加到 jar,但不使用它

java - 如何清除 JSONArray

c - 指向结构的指针数组

python - 是否有相当于 MATLAB 的 conv2(h1,h2,A ,'same' ) 的 python ?

javascript - 在数字和字符之间插入一个空格

java - JUnit + Spring 配置文件 : could not load JDBC driver class

arrays - MongoDB:匹配数组元素的计数

c# 将二进制数据读取到字符串中

java - 如何在 Java 中比较字符串?