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?
We know that a two-dimensional array in Java is a single-dimensional array having another single-dimensional array as its elements. We can use the Arrays. toString() method to print string representation of each single-dimensional array in the given two-dimensional array.
A list of strings can be stored within a 2D array. char str[3][15] = {""aaa"",""bbb"",""ccc""}; This represents an array with array name 'str' and it is of two dimensions. Here, 3 defines the number of strings that are stored in the array and the value 15 denotes the string length in total in the array.
Here's one naive implementation, which writes out one string per line (assuming that the strings don't have any newlines in them): std::ofstream output("result. txt"); for (size_t i = 0; i < 137; ++i) for (size_t j = 0; j < 42; ++j) output << myArray[i][j] << std::endl; Hope this helps!
The Arrays class defines a couple of useful methods
String[][] aastr = {{"hello", "world"},{"Goodbye", "planet"}}; System.out.println(Arrays.deepToString(aastr));
Gives
[[hello, world], [Goodbye, planet]]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With