我有一个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
有什么想法吗?
除非使用jre的旧版本,否则使用Vector
是不可修改的。我建议您迁移到List
,并相应地建立我的答案。此外,我很困惑你为什么转换为Integer。您可以像这样直接处理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
有这样的事情吗?
int[][] result = new int[myVec.size()][];
for(int i = 0; i < myVec.size(); i++) {
result[i] = myVec.get(i);
}