Join a string using delimiters

后端 未结 24 1660
北海茫月
北海茫月 2020-12-05 09:57

What is the best way to join a list of strings into a combined delimited string. I\'m mainly concerned about when to stop adding the delimiter. I\'ll use C# for my example

24条回答
  •  没有蜡笔的小新
    2020-12-05 10:37

    In .NET, I would use the String.join method if possible, which allows you to specify a separator and a string array. A list can be converted to an array with ToArray, but I don't know what the performance hit of that would be.

    The three algorithms that you mention are what I would use (I like the second because it does not have an if statement in it, but if the length is not known I would use the third because it does not duplicate the code). The second will only work if the list is not empty, so that might take another if statement.

    A fourth variant might be to put a seperator in front of every element that is concatenated and then remove the first separator from the result.

    If you do concatenate strings in a loop, note that for non trivial cases the use of a stringbuilder will vastly outperform repeated string concatenations.

提交回复
热议问题