Join a string using delimiters

后端 未结 24 1636
北海茫月
北海茫月 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 11:00

    I would express this recursively.

    • Check if the number of string arguments is 1. If it is, return it.
    • Otherwise recurse, but combine the first two arguments with the delimiter between them.

    Example in Common Lisp:

    (defun join (delimiter &rest strings)
      (if (null (rest strings))
          (first strings)
          (apply #'join
                 delimiter
                 (concatenate 'string
                              (first strings)
                              delimiter
                              (second strings))
                 (cddr strings))))
    

    The more idiomatic way is to use reduce, but this expands to almost exactly the same instructions as the above:

    (defun join (delimiter &rest strings)
      (reduce (lambda (a b)
                (concatenate 'string a delimiter b))
              strings))
    

提交回复
热议问题