2

Every once in a while, I need to build a character separated string while looping through a collection. Believe it or not, there is always that first or last separator character that gets in the way! :) Usually, I end up chopping off the extra character, which is another line of code. I could leave with that, but out of curiosity, does anyone have any cool "smooooth" way of doing this? (in C# and/or JavaScript)

Example:

{"Joe", "Jane", "Jim"}

After building comma separated string, we get:

"Joe, Jane, Jim, " or ", Joe, Jane, Jim"

Looking for a cool way to build

"Joe, Jane, Jim"

without any string "chopping" after.

Nicole
  • 32,841
  • 11
  • 75
  • 101
Dimskiy
  • 5,233
  • 13
  • 47
  • 66
  • I always think there must be a cleaner way, but I think chopping the last character off is quite efficient as you're not having to check on every iteration. Alternatively loop through all but the last and then append the last. – El Ronnoco May 10 '11 at 22:03
  • @El Ronnoco - Agree. I'd rather have a 1 line of "chopping" code instead of a nasty if statement in the middle of it :) – Dimskiy May 10 '11 at 22:12

5 Answers5

2

In Javascript it's easy:

var input = ["Joe", "Jane", "Jim"];

var str = input.join(','); // Output: Joe,Jane,Jim

Most languages have some form of "join" either built-in or in some library:


By the way, if you are writing such a function, you should just use a check to not prepend the "glue" on the first pass, rather than chopping the string afterward:

var items = ["joe","jane","john"];
var glue = ",";
var s = "";
for (var i=0; i < items.length; i++) {
    if (i != 0) s += glue;
    s += items[i];
}
Community
  • 1
  • 1
Nicole
  • 32,841
  • 11
  • 75
  • 101
2

Most languages have a join or implode function, which will take a collection or array or what-have-you and will 'join' the elements of that array with a string of your choosing.

Javascript:

array.join(',')

c#:

String.Join(',', array);
Dancrumb
  • 26,597
  • 10
  • 74
  • 130
1

In Javascript, if your collection is an array, you can call the join function on it:

var arr = ["Joe", "Jane", "Jim"]

var str = arr.join(",");

str here will give:

"Joe, Jane, Jim"
Mark Costello
  • 4,334
  • 4
  • 23
  • 26
0

Not as good as Mark Costello's answer but this works

Jay
  • 13,803
  • 4
  • 42
  • 69
0

If you have an Array, you can just arr.join(', ');. If you meant an object (the {}) then you have to iterate over.

var str ='';
for (var x in obj) if (obj.hasOwnProperty(x))
    str += (str.length ? ', ' : '') + obj[x];

Probably more efficient, although I doubt it matters.

var str ='', append = false;
for (var x in obj) if (obj.hasOwnProperty(x)) {
    str += (append ? ', ' : '') + obj[x];
    append = true;
}
Robert
  • 21,110
  • 9
  • 55
  • 65