简体   繁体   中英

Convert vector of integers into a 2D array

I had a String and I was able to convert it into a 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;
}}

Now I want to convert it into a 2D int array ( int[][] ). For example if I have [0,1,0,0] it will become a column vector, something like this

0
1
0
0  

Any ideas?

Somthing like this?

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

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

Working with Vector is unadvised unless you use an ancient version of the jre. I suggest you migrate to List and base my answer accordingly. Also, i'm puzzled why you convert to Integer. You can work directly on the char[] like this.


You can try the following for an input like this [[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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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