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

前端 未结 7 825
轮回少年
轮回少年 2020-12-20 17:28

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 othe

7条回答
  •  余生分开走
    2020-12-20 18:06

    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

提交回复
热议问题