g_strsplit variant which filters empty strings from the result



Hi all.

I've needed g_strsplit function version which filters empty strings from
result. For example I'd like g_strsplit ("/any//path", "/", 0) return
{"any", "path"} but not {"", "any", "", "path"}. I didn't find such
function variant so I slightly modified Glib' g_strsplit. Here is the
result:

gchar**
g_strsplit_no_empty (const gchar *string,
                     const gchar *delimiter,
                     gint         max_tokens)
{
  GSList *string_list = NULL, *slist;
  gchar **str_array, *s;
  guint n = 0;
  const gchar *remainder;

  g_return_val_if_fail (string != NULL, NULL);
  g_return_val_if_fail (delimiter != NULL, NULL);
  g_return_val_if_fail (delimiter[0] != '\0', NULL);

  if (max_tokens < 1)
    max_tokens = G_MAXINT;

  remainder = string;
  s = strstr (remainder, delimiter);
  if (s)
    {
      gsize delimiter_len = strlen (delimiter);

      while (--max_tokens && s)
        {
          gsize len;

          len = s - remainder;
          if (len != 0)
            {
              string_list = g_slist_prepend (string_list,
                                             g_strndup (remainder,
len));
              n++;
            }
          remainder = s + delimiter_len;
          s = strstr (remainder, delimiter);
        }
    }
  if (*string)
    {
      n++;
      string_list = g_slist_prepend (string_list, g_strdup (remainder));
    }

  str_array = g_new (gchar*, n + 1);

  str_array[n--] = NULL;
  for (slist = string_list; slist; slist = slist->next)
    str_array[n--] = slist->data;

  g_slist_free (string_list);

  return str_array;
}

It will be nice if Glib included a such function variant. What do you
think?

Alexander



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