Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm for joining e.g. an array of strings

I have wondered for some time, what a nice, clean solution for joining an array of strings might look like. Example: I have ["Alpha", "Beta", "Gamma"] and want to join the strings into one, separated by commas – "Alpha, Beta, Gamma".

Now I know that most programming languages offer some kind of join method for this. I just wonder how these might be implemented. When I took introductory courses, I often tried to go it alone, but never found a satisfactory algorithm. Everything seemed rather messy, the problem being that you can not just loop through the array, concatenating the strings, as you would add one too many commas (either before or after the last string). I don’t want to check conditions in the loop. I don’t really want to add the first or the last string before/after the loop (I guess this is maybe the best way?).

Can someone show me an elegant solution? Or tell me exactly why there can’t be anything more elegant?

like image 523
knuton Avatar asked Sep 12 '08 07:09

knuton


People also ask

How do you join an array of strings?

join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

How do you join strings?

The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator.

How do you concatenate elements in an array in Java?

Example 1: Concatenate Two Arrays using arraycopy Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function. The arraycopy(array1, 0, result, 0, aLen) function, in simple terms, tells the program to copy array1 starting from index 0 to result from index 0 to aLen .


1 Answers

The most elegant solution i found for problems like this is something like this (in pseudocode)

separator = ""
foreach(item in stringCollection)
{
    concatenatedString += separator + item
    separator = ","
}

You just run the loop and only after the second time around the separator is set. So the first time it won't get added. It's not as clean as I'd like it to be so I'd still add comments but it's better than an if statement or adding the first or last item outside the loop.

like image 179
Mendelt Avatar answered Sep 27 '22 22:09

Mendelt