将整数向量转换为2D数组

时间:2013-07-24 10:44:19

标签: java matrix converter

我有一个String,我可以将其转换为Vector<Integer>

public class VectorConverter {
public static Vector <Integer> v (String s) {
    Vector<Integer> myVec = new Vector();

    //Convert the string to a char array and then just add each char to the vector
    char[] sChars = s.toCharArray();
    int[] sInt= new int [sChars.length];;
    for(int i = 0; i < s.length(); ++i) {
        sInt[i]= Character.getNumericValue(sChars[i]);
        myVec.add(sInt[i]);
    }

    return myVec;
}}

现在我想将其转换为2D int数组(int[][])。例如,如果我有[0,1,0,0],它将成为列向量,类似这样

0
1
0
0  

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

这样的东西?

int[][] result = new int[myVec.size()][];

for(int i = 0; i < myVec.size(); i++) {
   result[i] = myVec.get(i);
}

答案 1 :(得分:0)

除非您使用古老版本的jre,否则未使用Vector。我建议你迁移到List并根据我的答案做出相应的答案。 此外,我很困惑为什么你转换为整数。 你可以像这样直接在char []上工作。


您可以尝试以下输入,例如[[4,2,6][....]]

ArrayList<ArrayList<Integer>> table = new ArrayList<ArrayList<Integer>>();
char[] chars = myString.toCharArray();
ArrayList<Integer> current = null;
for(int i=1; i<chars.length-1; ++i) { // To avoid parsing begining and end of the array
    char c = chars[i];
    if(c == '[')
        table.add(current = new ArrayList<Integer>());
    if(c == ']')
        continue;
    current.add(Character.getNumericValue(c));
}
int[][] result = table.toArray(new int[0][0]); // Maybe this will fail and you'll have to use Integer[][] instead
相关问题