How to print two dimensional array of strings as String
java, multidimensional-array, string
Solution
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.
Problem
I know how to do the `toString` method for one dimensional arrays of strings, but how do I print a two dimensional array? With 1D I do it this way: ``` public String toString() { StringBuffer result = new StringBuffer(); res = this.magnitude; String separator = ""; if (res.length > 0) { result.append(res[0]); for (int i=1; i<res.length; i++) { result.append(separator); result.append(res[i]); } } return result.toString(); ``` How can I print a 2D array?