Note that there are some explanatory texts on larger screens.

plurals
  1. POJoin a string using delimiters
    primarykey
    data
    text
    <p>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 examples but I would like this to be language agnostic.</p> <p>EDIT: I have not used StringBuilder to make the code slightly simpler.</p> <p><strong>Use a For Loop</strong></p> <pre class="lang-cs prettyprint-override"><code>for(int i=0; i &lt; list.Length; i++) { result += list[i]; if(i != list.Length - 1) result += delimiter; } </code></pre> <p><strong>Use a For Loop setting the first item previously</strong></p> <pre class="lang-cs prettyprint-override"><code>result = list[0]; for(int i = 1; i &lt; list.Length; i++) result += delimiter + list[i]; </code></pre> <p>These won't work for an IEnumerable where you don't know the length of the list beforehand so </p> <p><strong>Using a foreach loop</strong></p> <pre class="lang-cs prettyprint-override"><code>bool first = true; foreach(string item in list) { if(!first) result += delimiter; result += item; first = false; } </code></pre> <p><strong>Variation on a foreach loop</strong></p> <p>From Jon's solution</p> <pre class="lang-cs prettyprint-override"><code>StringBuilder builder = new StringBuilder(); string delimiter = ""; foreach (string item in list) { builder.Append(delimiter); builder.Append(item); delimiter = ","; } return builder.ToString(); </code></pre> <p><strong>Using an Iterator</strong></p> <p>Again from Jon</p> <pre class="lang-cs prettyprint-override"><code>using (IEnumerator&lt;string&gt; iterator = list.GetEnumerator()) { if (!iterator.MoveNext()) return ""; StringBuilder builder = new StringBuilder(iterator.Current); while (iterator.MoveNext()) { builder.Append(delimiter); builder.Append(iterator.Current); } return builder.ToString(); } </code></pre> <p>What other algorithms are there?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload