Join a string using delimiters

后端 未结 24 1648
北海茫月
北海茫月 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:51

    I thint the best way to do something like that is (I'll use pseudo-code, so we'll make it truly language agnostic):

    function concat( list,  strict):
      for i in list:
        if the length of i is zero and strict is false:
          continue;
        if i is not the first element:
          result = result + separator;
        result = result + i;
      return result;
    

    the second argument to concat(), strict, is a flag to know if eventual empty strings have to be considered in concatenation or not.

    I'm used to not consider appending a final separator; on the other hand, if strict is false the resulting string could be free of stuff like "A,B,,,F", provided the separator is a comma, but would instead present as "A,B,F".

提交回复
热议问题