Re: [GLib] How to get substrings?



On Tue, 2004-11-09 at 08:26, Iago Rubio wrote:
gchar*
substring_between( gchar* haystack, gchar* needle1, gchar* needle2)
{
        gchar* pos1;
        gchar* pos2;
        gchar* strcopy;
        gchar* retval;

        if( haystack == NULL || needle1 == NULL || needle2 == NULL )
              return NULL;
        strcopy = g_strdup(haystack);
        pos1 = g_strrstr( (const gchar*) strcopy,
                           (const gchar*) needle1 );
        if( pos1 == NULL) {
              g_free(strcopy);
              return NULL;
      }
        pos2 =  g_strrstr( (const gchar*) pos1,
                           (const gchar*) needle2);
        if( pos2 == NULL ) { 
              g_free(strcopy); 
              return NULL;
      }
        if( (pos1 += strlen(needle1)) >= pos2) {
              g_free(strcopy);
              return NULL;
      }
        *pos2 = '\0';
        retval =  g_strdup(pos1);
        g_free(strcopy);
        return retval;
}

Isn't that a bit much? How about...

gchar*
substring_between2(gchar* haystack, gchar* needle1, gchar* needle2)
{
    gchar* pos1;
    gchar* pos2;

    if( haystack == NULL || needle1 == NULL || needle2 == NULL )
        return NULL;
    pos1 = g_strrstr( (const gchar*) haystack,
                       (const gchar*) needle1 );
    if( pos1 == NULL )
        return NULL;
    pos2 =  g_strrstr( (const gchar*) pos1,
                       (const gchar*) needle2);
    if( pos2 == NULL )
        return NULL;
    if( (pos1 += strlen(needle1)) >= pos2 ) {
        /* not entirely correct - if pos1==pos2, we should probably 
         * return a zero-length string, not null */
        return NULL;
    }
    return g_strndup(pos1, pos2-pos1);
}

Does somewhat less allocating/deallocating. Although I'm
compelled to admit that I've not tried to compile either
version. Also should be noted that, if these work at all,
they will find the last occurance, not the first, which I
think would be more natural.





[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]