views:

33

answers:

2

Trying to stay completely language agnostic, and avoiding built in methods like Split() and Join(), what are the most utilized or accepted methods to build a CSV string? I run into situations like this a lot, and I'm curious as to how methods like Split() implement this? I usually do something like this:

for(int i = 0; i < list.length; i++)
{
    if(i == list.length - 1)
    {
        Write(list[i]);
    }
    else
    {
        Write(list[i] + ',');
    }
}

But it seems like there should be a better way to do it.

+3  A: 

Most implementations I've seen do something more like:

if (list.length > 0)
{
    Write(list[0]);
    for(int i = 1; i < list.length; i++)
    {
        Write(','); // Write separator character(s)
        Write(list[i]);
    }
}

This avoids the checking inside the for loop. The .NET Framework's Join() method uses this basic approach (with a lot more checking, of course).

Reed Copsey
This is exactly what I was looking for, Thanks!
MGSoto
A: 

You probably don't want to use Split, Join, or anything simplistic. What if your value contains a comma or a quote?

If possible, use a library. Otherwise, something like:

string escapeForCsv(string s) {
    if s.contains("\",\n") {
      needs_quotes = true
      s.replace("\"", "\"\"")
    }
    if needs_quotes {
      s = "\"" + s + "\""
    }
    return s
}

for (i := 0; i < array.length; i++) {
    elt = array[i]
    if i > 0 {
       Write(',')
    }
    Write(escapeForCsv(elt))
}
Kyle C