0

Using strsep to split a CSV with a bunch of usless junk in it ("," Delim). One of the entries has quotes on either side (ie Florida,"Bob",1999) and I'd like to pull those out before I save them in my array.

How do I remove the quotes from the name? Thanks!

for (int i = 0; i < 19; i++)
{                               
  token = strsep(&copy, ","); //Split token
  if (i ==  3) {one_spot->location = token;}
  if (i == 17) {one_spot->name = token;}//the Name is in quotes in CSV
  if (i == 18) {one_spot->year = atoi(token);}
}
all_spots[j] = one_spot; //Add to array.
SsedOut
  • 41
  • 3
  • What's your question? – John Kugelman Jan 28 '18 at 18:18
  • 1
    First of all, you should really not try to make your own CSV parser. While it might seem simple and trivial, there are quite a few corner and special cases that are non-trivial to handle. For example, the existence of the double-quotes indicates that it could be an arbitrary string containing spaces and other special characters, including *commas*. – Some programmer dude Jan 28 '18 at 18:18
  • As for your problem, remember that a C string is basically just an array with a special terminator character. Now what happens if you place this terminator character in the middle of the string? What happens if you get a pointer to the second character in the string? Think about that a little, and do some experimentation. – Some programmer dude Jan 28 '18 at 18:20

1 Answers1

0

You could do something like this:

  1. look for the first " using strchr
  2. If found, look for the next "
  3. Use memcpy to copy the strings between the quotes.

if (i == 17)
{
    char *firstq = strchr(token, '"');
    if(firstq == NULL)
    {
        one_song->name = strdup(token);
        continue;
    }

    char *lastq = strchr(firstq++, '"');
    if(lastq == NULL)
    {
        // does not end in ", copy everything
        one_song->name = strdup(token);
        continue;
    }

    size_t len = lastq - firstq;

    char *word = calloc(len + 1, 1);
    if(word == NULL)
    {
        // error handling, do not continue
    }

    memcpy(word, firstq, len); // do not worry about \0 because of calloc
    one_song->name = word;
}

Note that I use strdup to do the assignment one_song->name = strdup(token); and calloc to allocate memory. strsep returns a pointer to copy + an offset. Depending how you created/allocated copy, this memory might be invalid once the function exits. That's why it's better to create a copy of the original before you assign it to the struct.

This code is very simple, it does not handle spaces at the beginning and end of the string. It can distinguish between abc and "abc" but it fails at "abc"d or "abc"def". It also does not handle escaped quotes, etc. This code shows you only a way of extracting a string from the quotes. It's not my job to write your exercise for you, but I can show you how to start.

Pablo
  • 13,271
  • 4
  • 39
  • 59