简体   繁体   English

将字符串数组拆分为 int 数组

[英]Split string array to int array

I want to convert array of strings, for example我想转换字符串数组,例如

str1[][] ={{"1,2,3,4","0","2,1"}};

to int array like that:像这样的int数组:

int arr[][]={{1,2,3,4},{0,0,0,0},{2,1,0,0}} 

Im not able to use just split method, because the size of the tempString changes after every iteration.我不能只使用 split 方法,因为每次迭代后 tempString 的大小都会改变。

My code:我的代码:

int numOfelements = 3;

        String str1[][] = { { "1,2,3,4", "0", "2,1" } };
        int graph[][] = new int[numOfelements][numOfelements];
        String str[]= new String[numOfelements];


            for (int i = 0; i < numOfelements; ++i) {
                str = str1[i][0].split(",");
                for (int j = 0; j < numOfelements; ++j) {
                    try {
                        if (str.length < j)
                            graph[i][j] = Integer.parseInt(str[i]);
                        else
                            graph[i][j] = 0;
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(new JFrame(), "Error in the data!",
                                "Error", JOptionPane.ERROR_MESSAGE);
                        break;
                    }
                }
            }

You may write a customized method to fill the array with zeroes.您可以编写自定义方法来用零填充数组。 .split() still can be used if you use it cautiously.如果您谨慎使用.split()仍然可以使用它。

public static int[] fillArray(String s, int size){
    String[] tok = str.split(",");
    int[] newArr = new int[size];

    for(int x=0; x<Math.min(size, tok.length); x++)
        newArr[x] = Integer.parseInt(tok[x]);

    for(int x=Math.min(size, tok.length); x<Math.max(size, tok.length); x++)
        newArr[x] = 0;

    return newArr;
}

Get the array data and fill it with zeroes and put it back in a new array:获取数组数据并用零填充并将其放回新数组中:

int[][] arr;
for(int x=0; x<str1[0].length; x++)
    arr[0][x] = fillArray(str1[0][x], 4);  //size of 4 can be changed to your needs

try this solution :试试这个解决方案:

int numOfelements = 4;
        String str1[][] = { { "1,2,3,4", "0", "2,1" }};
        int graph[][] = new int[numOfelements][numOfelements];
        String str[]= new String[numOfelements];

        for (int k = 0; k < str1.length; k++) {
            int len =str1[k].length;    
            for (int i = 0; i < len; i++) {
                str = str1[k][i].split(",");    
                for(int j = 0; j < str.length; j++ )
                    graph[i][j]=Integer.parseInt(str[j]);
            }
        }

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

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