Java is the future !: Converting a 2d array of ints to char and string in Java

Saturday, November 6, 2010

Converting a 2d array of ints to char and string in Java

Question How can i convert the ints in a 2d array into chars, and strings?

If i copy ints to a char array i just get the ascii code.
For example
public int a[5][5]
//some code
public String b[5][5] = public int a[5][5]
Answer : Quite frankly, the easiest approach would simply leave your array as-is... and convert int values toString's when you use them:

Alternatively, you could start with a String[][] array in the first place, and simply convert your intvalues to String when adding them:
a[5][5] = new String(myInt);
If you really do need to convert an array of type int[][] to one of type String[][], you would have to do so manually with a two-layer for() loop:
String[][] converted = new String[a.length][];
for(int index = 0; index < a.length; index++) {
    converted[index] = new String[a[index].length];
    for(int subIndex = 0; subIndex < a[index].length; subIndex++){
        converted[index][subIndex] = Integer.toString(a[index][subIndex]);
All three of these approaches would work equally well for conversion to type char rather thanString.

Source : Stack-Overflow

No comments:

Post a Comment