Ayush
Ayush

Reputation: 42450

Printing a comma (,) after each item in an array

Lets say I have an array (or list) of items

A[] = [a,b,c,d,e]

If I want to print them out so each item is separated by a comma (or any other delimiter), I generally have to do this:

for(int i=0; i < A.Count; i++)
{
    Console.Write(A[i]);

    if (i != A.Count-1)
        Console.Write(",");
}

So, my output looks like:

a,b,c,d,e

Is there a better or neater way to achieve this?

I like to use a foreach loop, but that prints a comma after the last element as well, which is undesirable.

Upvotes: 9

Views: 11936

Answers (7)

MEC
MEC

Reputation: 1736

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        string[] values = new string[]{"banana", "papaya", "melon"};

        var result = values.Aggregate((x,y) => x + ", " + y);

        Console.WriteLine(result);
    }
}

Upvotes: 1

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35126

string separator = String.Empty;
for(int i=0; i < A.Length; i++)
{
    Console.Write(seperator);
    Console.Write(A[i]);
    separator = ",";
}

Upvotes: 2

Eric Lippert
Eric Lippert

Reputation: 660038

Is there a better or neater way to achieve this? I like to use a foreach loop, but that prints a comma after the last element as well, which is undesirable.

As others have said, Join does the right thing. But here's another way to think about the problem that might help you in the future. Instead of thinking of the problem as put a comma after every element except the last element -- which you correctly note makes it difficult to work with the "foreach" loop -- think of the problem as put a comma before every element except the first element. Now it is easy to do with a foreach loop!

For about a million more ways to solve a similar problem see:

Eric Lippert's challenge "comma-quibbling", best answer?

And the original blog post:

http://blogs.msdn.com/b/ericlippert/archive/2009/04/15/comma-quibbling.aspx

Upvotes: 6

Anas Karkoukli
Anas Karkoukli

Reputation: 1342

Use:

String.Join(",", arrayOfStrings);

Upvotes: 3

Gishu
Gishu

Reputation: 136613

Use the string.Join method, very handy.

String.Join(",", my_array)

Upvotes: 4

NullUserException
NullUserException

Reputation: 85458

You are looking for String.Join():

var list = String.join(",", A);

String.Join Method (String, String[])

 Concatenates all the elements of a string array, using the specified separator between each element.

public static string Join(
    string separator,
    params string[] value
)

Upvotes: 9

Bala R
Bala R

Reputation: 108957

Console.WriteLine(string.Join(",", A));

Upvotes: 28

Related Questions