g_strsep implementation



glib has a bunch of nice string functions, but one glaring omission is
strsep. So here's a patch to implement g_strsep.

I think it's small enough to go in for 1.2, and it rounds out glib's
string portability functions nicely.

-Yosh
Index: glib.h
===================================================================
RCS file: /cvs/gnome/glib/glib.h,v
retrieving revision 1.111
diff -u -r1.111 glib.h
--- glib.h	1999/01/17 15:21:28	1.111
+++ glib.h	1999/02/07 11:22:57
@@ -1428,6 +1428,8 @@
 gint	 g_strncasecmp		(const gchar *s1,
 				 const gchar *s2,
 				 guint 	      n);
+gchar*	 g_strsep		(gchar      **string,
+				 const gchar *delim);
 void	 g_strdown		(gchar	     *string);
 void	 g_strup		(gchar	     *string);
 void	 g_strreverse		(gchar	     *string);
Index: gstrfuncs.c
===================================================================
RCS file: /cvs/gnome/glib/gstrfuncs.c,v
retrieving revision 1.24
diff -u -r1.24 gstrfuncs.c
--- gstrfuncs.c	1999/01/25 12:45:51	1.24
+++ gstrfuncs.c	1999/02/07 11:22:57
@@ -1056,6 +1056,38 @@
 }
 
 gchar*
+g_strsep (gchar       **string,
+    	  const gchar *delim)
+{
+  gchar *p, *q;
+  
+  if (!(p =* string))
+    return NULL;
+  
+  if (delim[0] == '\0' || delim[1] == '\0')
+    {
+      gchar ch = delim[0];
+      
+      if (ch != '\0')
+        q = (*p == ch) ? p : strchr (p + 1, ch);
+      else
+	q = NULL;
+    }
+  else
+    q = strpbrk (p, delim);
+  
+  if (q)
+    {
+      *q++ = '\0';
+      *string = q;
+    }
+  else
+    *string = NULL;
+  
+  return p;
+}
+
+gchar*
 g_strescape (gchar *string)
 {
   gchar *q;
Index: tests/strfunc-test.c
===================================================================
RCS file: /cvs/gnome/glib/tests/strfunc-test.c,v
retrieving revision 1.1
diff -u -r1.1 strfunc-test.c
--- strfunc-test.c	1999/01/21 18:07:20	1.1
+++ strfunc-test.c	1999/02/07 11:22:57
@@ -91,6 +91,15 @@
   g_assert (strcmp(string, "00021 test ") == 0);
   g_free (string);
 
+  string = g_strdup ("foo, bar, baz");
+  g_assert (strcmp (g_strsep (&string, ", "), "foo") == 0);
+  g_assert (strcmp (g_strsep (&string, ", "), "") == 0);
+  g_assert (strcmp (g_strsep (&string, ", "), "bar") == 0);
+  g_assert (strcmp (g_strsep (&string, ", "), "") == 0);
+  g_assert (strcmp (g_strsep (&string, ", "), "baz") == 0);
+  g_assert (g_strsep (&string, ", ") == NULL);
+  g_free (string);
+
   return 0;
 }
 


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