csplitstrsep

strsep() function - more characters in delimiter


I am having problems using the strsep() function in C. I want to split a string into two parts. The string contains info about the currently playing song, in ARTIST - TITLE format, so artist and title are separated by one space, one dash and again one space. I want to separate it by this, " - ". "-" won't work because some artists have a dash in their name.

When I try this code with, for example, "Michel Telo - Ai Se Eu Te Pego":

// String is in tmp
while ((token = strsep(&tmp, " - ")) != NULL)
{
    printf("%s\n", token);
}

I get this:

[root@runeaudio ~]# ./board
Michel
Telo


Ai
Se
Eu
Te
Pego

Instead of this:

[root@runeaudio ~]# ./board
Michel Telo
Ai Se Eu Te Pego

Seems like strsep() is dividing delimiter into 3 characters: " ", "-", " " and using OR between them, but I want it to look for " - " as it is. Any idea how to fix this?


Solution

  • The following code, demonstrate how you can split the string, it's not very useful because it does nothing with the tokens except for printing them, but you can see how it works and implement a version that does what you need.

    char string[] = "Michel Telo - Ai Se Eu Te Pego";
    char *separator = strstr(string, " - ");
    if (separator != NULL)
     {
         separator[0] = '\0';
         printf("%s\n", string);
    
         separator[0] = ' ';
         printf("%s\n", separator + 3);
     }
    

    You can of course use strdup() or similar function to create new strings with the contents of the "tokens".

    This is of course not robust, because nothing can ensure that there wont be an artist with " - " in it's name, if it's in the song name however, it's not so bad.

    This is a working version, if you don't have strdup() on your platform there will surely be an implementation of it with a different name

    #include <string.h>
    
    void extractArtistAndTitle(char *string, char **artist, char **title)
     {
        char *separator;
    
        if ((string == NULL) || (artist == NULL) || (title == NULL))
            return;
        separator = strstr(string, " - ");
        if (separator != NULL)
         {
            size_t length;
    
            length  = separator - string;
            *artist = malloc(1 + length);
            if (*artist != NULL)
            {
                memcpy(*artist, string, length);
               (*artist)[length] = '\0';
            }
            *title = strdup(separator + 3);
         }
     }
    
    int main()
    {
        char string[] = "Michel Telo - Ai Se Eu Te Pego";
        char *artist;
        char *title;
    
        extractArtistAndTitle(string, &artist, &title);
        if (artist != NULL)
            printf("Artist: %s\n", artist);
        if (title != NULL)
            printf("Title : %s\n", title);
        free(artist);
        free(title);
    
        return 0;
    }