algorithms – How to create a text string with separators efficiently?

Question:

This question is to share a very simple trick that I learned on StackOverflow and that has served to clean thousands of cases in my code.

NOTE: it is not a translation, it is simply a transmission of knowledge that I think is necessary and interesting and originally created by me for OS in Spanish.


We have all assembled a text string by hand by inserting the separators, for example:

  • Characteristics of an element (car) separated by commas ,

     ABS, ESP, EE, CC
  • List to print with line breaks \n

     producto1 2,23\n producto2 3,23\n producto33 5,31\n

And we have encountered one of the following problems:

  • insert a comparison at each iteration:

    JAVA

     // bucle que inserta valor v en variable x if ("".equals(x)) x = v; else x = "," + v;

    JAVASCRIPT

     // bucle que inserta valor v en variable x if (x == "") x = v; else x = "," + v;
  • If we do not insert that comparison to optimize, we also have to do it later to avoid

    • last empty element:

       1,1,1,1,1, // ↑ aquí!
    • first empty element

       ,1,1,1,1,1 //↑ aquí!

QUESTION

Is there a pattern to avoid this usual and annoying case and that meets the following characteristics?

  • Transversal (usable in any language).
  • Optimal (avoid expensive functions / methods, extra comparisons or iterations)
  • Readable

Answer:

This is another way of looking at it.

In cases where you work with items, and add them, the ideal is to use an array .

And from there:

  1. array.push() adds an element to the array
  2. array.join() concatenates all elements with a separator

Code

 var separador = ','; var items = []; //array vacío for (var i = 0; i < 10; i++) { // agrega 1 elemento al array items.push(i); } //concatena con separador var arrayManual = items.join(separador) // mostrar el resultado resultado.innerText = arrayManual;
 <pre id="resultado"></pre>
Scroll to Top