Algorithm for joining e.g. an array of strings

后端 未结 16 1859
陌清茗
陌清茗 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:16

    Most languages nowadays - e.g. perl (mention by Jon Ericson), php, javascript - have a join() function or method, and this is by far the most elegant solution. Less code is better code.

    In response to Mendelt Siebenga, if you do require a hand-rolled solution, I'd go with the ternary operator for something like:

    separator = ","
    foreach (item in stringCollection)
    {
        concatenatedString += concatenatedString ? separator + item : item
    }
    

提交回复
热议问题