You could do something like this:
- look for the first
"
using strchr
- If found, look for the next
"
- 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.