C# Join function took all the fun out of trivial programming. In the old days creating a comma separated string out of an array of string was a daunting task for junior programmers.

Some would use the postfix technique. Typically they would iterate through an array adding a comma after each string. At the end they would remove the last comma. But only if string was not empty.

Another approach was to add a comma only if string was not the last in the array. This meant abandoning foreach loop to be able to compare index to array size.

There is a much more elegant solution. It might not be useful in C# because the string class already provides this function, but it is a good to know algorithm.

string Join(string separator, string[] array)
{
    StringBuilder sb = new StringBuilder();    
    string prefix = null;
    foreach (string s in array)
    {
        sb.Append(prefix);
        sb.Append(s);
        prefix = separator;
    }
    return sb.ToString();
}

0 comment(s) :

Older Post Home

Blogger Syntax Highliter