Algorithm for joining e.g. an array of strings

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

    The most elegant solution i found for problems like this is something like this (in pseudocode)

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

    You just run the loop and only after the second time around the separator is set. So the first time it won't get added. It's not as clean as I'd like it to be so I'd still add comments but it's better than an if statement or adding the first or last item outside the loop.

提交回复
热议问题