简体   繁体   English

有没有一种方法可以从字符串遍历到int数组,反之亦然

[英]Is there a way of traversing from string to int array and vice versa

In Java, given the array 在Java中,给定数组

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

I can do Arrays.toString(a) to get 我可以做Arrays.toString(a)得到

"[1,2,3]"

Is there an equally convenient way to return this String back to its antecedent array? 是否有同样方便的方法将此String返回其先前的数组? Or must I go through the whole split , for-loop, parseInt stuff? 还是我必须遍历整个split ,for循环, parseInt内容?

UPDATE UPDATE

Thanks everyone for all the thoughts. 感谢大家的所有想法。 I rolled out my own function as 我推出了自己的功能

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;

Note: the word traverse seems to have thrown a few people off. 注意:“遍历”一词似乎使一些人失望了。 By "traversing" I meant the ability to move back and forth from the string to the int array. “遍历”是指从字符串到int数组来回移动的能力。

As far as i know, no. 据我所知,没有。

But it's easy to do using Split . 但是使用Split很容易做到。

I just did this, if you don't understand how to do it: 如果您不了解该如何做,我就是这样做的:

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));

(free to improve it, it's just a draft) (可以免费进行改进,只是草稿)

I don't know of any existing method, so I wrote you my own version: 我不知道任何现有方法,因此我为您编写了自己的版本:

import java.util.Arrays;


public class ArrayToString {

    public static void main(String[] args) {
        int a[] = {1,2,3};
        String serialized = Arrays.toString(a);
        System.out.println(serialized);

        int[] b = stringToIntArray(serialized);

        System.out.println(Arrays.toString(b));
    }

    private static int[] stringToIntArray(String serialized) {

        // remove '[' and ']'
        String raw = serialized.replaceAll("^\\[(.*)\\]$", "$1");

        // split by separators
        String[] splitStrings = raw.split(", ");

        // create new int array
        int[] b = new int[splitStrings.length];
        for (int i = 0; i < splitStrings.length; i++) {
            String splitString = splitStrings[i];

            // parse each text individually
            b[i] = Integer.parseInt(splitString);
        }
        return b;
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM