Home > Back-end >  Printing multidimensional array as CSV in console
Printing multidimensional array as CSV in console

Time:01-23

I have trouble doing it as my code appends an extra comma at the end of every row

How can I remove the last comma?

CodePudding user response:

You can use a StringBuilder to create the rows. It allows you to removed added text by decreasing the Length property and it is also more efficient than string concatenation.

var a = new int[,] { { ... }, ... };

const char Separator = ',';

var row = new StringBuilder();
for (int i = 0; i < a.GetLength(0); i  ) {
    row.Clear();
    for (int j = 0; j < a.GetLength(1); j  ) {
        row.Append(a[i, j]).Append(Separator);
    }
    row.Length--; // Remove last comma.
    Console.WriteLine(row);
}   
Console.ReadKey();

CodePudding user response:

int[,] array_1 = new int[3, 4]
{
    { 12,12,23,34 },
    { 32,43,12,45 },
    { 54,21,12,43 }
};

for (int i = 0; i < array_1.GetLength(0); i  )
{
    for (int j = 0; j < array_1.GetLength(1); j  )
    {
        int a = array_1[i, j];
        if (j!=3)
        {
            Console.Write(a ", ");
        }
        else
        {
            Console.Write(a);

        }
    }

    Console.WriteLine();
}   
Console.ReadLine();
  •  Tags:  
  • Related