Algorithm for joining e.g. an array of strings

后端 未结 16 1774
陌清茗
陌清茗 2021-01-01 21:40

I have wondered for some time, what a nice, clean solution for joining an array of strings might look like. Example: I have [\"Alpha\", \"Beta\", \"Gamma\"] and want to join

16条回答
  •  执笔经年
    2021-01-01 22:18

    I usually go with something like...

    list = ["Alpha", "Beta", "Gamma"];
    output = "";
    separator = "";
    for (int i = 0; i < list.length ; i++) {
      output = output + separator;
      output = output + list[i];
      separator = ", ";
    }
    

    This works because on the first pass, separator is empty (so you don't get a comma at the start, but on every subsequent pass, you add a comma before adding the next element.

    You could certainly unroll this a little to make it a bit faster (assigning to the separator over and over isn't ideal), though I suspect that's something the compiler could do for you automatically.

    In the end though, I suspect pretty this is what most language level join functions come down to. Nothing more than syntax sugar, but it sure is sweet.

提交回复
热议问题