Search code examples
c#matrixmultidimensional-arrayoverridingtostring

How to print matrix?


public override string ToString() {
    string matrixView = "";

    for (int r=0; r<=this.rows; r++) {
        for (int c=0; c<=this.columns; c++) {
                
        }
    }

    return matrixView;
}

Note:
##################################
this.rows = row number
this.columns = column number
this.matrix= 2-dimensional array used as data store
##################################

In this code, I aim to make seem for example 4x4 matrix like:

[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]

Each newline must be started with "[". Values(this.columns times) and spaces(this.columns-1 times) must be printed. Finally, the line must be ended with "]\n" And these operations above must be done this.rowstimes.

I think in this way. But nested loops always make me confuse. So, I tried several times but I couldn't be successful at it. And String.Concat threw NullReferenceExceptionwhen I tried to concaten matrixView with "[", "]\n" and this.matrix[r, c].ToString().


Solution

  • I think you are looking for something like this:

    public override string ToString() {
        // When building string, better use StringBuilder instead of String
        StringBuilder matrixView = new StringBuilder();
    
        // Note r < matrix.GetLength(0), matrix is zero based [0..this.rows - 1]
        // When printing array, let's query this array - GetLength(0)
        for (int r = 0; r < matrix.GetLength(0); r++) {
            // Starting new row we should add row delimiter 
            if (r > 0)
                matrixView.AppendLine();
    
            // New line starts from [
            matrixView.Append("["); 
    
            // Note r < matrix.GetLength(1), matrix is zero based [0..this.rows - 1]
            for (int c = 0; c < matrix.GetLength(1); c++) {
                // Starting new column we should add column delimiter 
                if (c > 0)
                    matrixView.Append(' ');
    
                matrixView.Append(matrix[r, c]);       
            }
    
            // New line ends with [
            matrixView.Append("]");
        }
    
        return matrixView.ToString();
    }