开发者

What's a good way to build a character separated string from a collection?

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 sepa开发者_开发问答rator 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.


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:

  • Javascript — it's a native function on the Array prototype
  • PHP — implode
  • Java — Apache Commons Lang
  • C# — String.Join

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];
}


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);


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"


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


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜