How to print two dimensional array of strings as String
You just iterate twice over the elements:
StringBuffer results = new StringBuffer();
String separator = ","
float[][] values = new float[50][50];
// init values
for (int i = 0; i < values.length; ++i)
{
result.append('[');
for (int j = 0; j < values[i].length; ++j)
if (j > 0)
result.append(values[i][j]);
else
result.append(values[i][j]).append(separator);
result.append(']');
}
IMPORTANT: StringBuffer
are also useful because you can chain operations, eg: buffer.append(..).append(..).append(..)
since it returns a reference to self! Use synctactic sugar when available..
IMPORTANT2: since in this case you plan to append many things to the StringBuffer
it's good to estimate a capacity to avoid allocating and relocating the array many times during appends, you can do it calculating the size of the multi dimensional array multiplied by the average character length of the element you plan to append.
The Arrays class defines a couple of useful methods
- Arrays.toString - which doesn't work for nested arrays
- Arrays.deepToString - which does exactly what you want
String[][] aastr = {{"hello", "world"},{"Goodbye", "planet"}};
System.out.println(Arrays.deepToString(aastr));
Gives
[[hello, world], [Goodbye, planet]]
public static <T> String to2DString(T[][] x) {
final String vSep = "\n";
final String hSep = ", ";
final StringBuilder sb = new StringBuilder();
if(x != null)
for(int i = 0; i < x.length; i++) {
final T[] a = x[i];
if(i > 0) {
sb.append(vSep);
}
if(a != null)
for(int j = 0; j < a.length; j++) {
final T b = a[j];
if(j > 0) {
sb.append(hSep);
}
sb.append(b);
}
}
return sb.toString();
}