Added silc_string_split.
authorPekka Riikonen <priikone@silcnet.org>
Tue, 7 Nov 2006 16:45:01 +0000 (16:45 +0000)
committerPekka Riikonen <priikone@silcnet.org>
Tue, 7 Nov 2006 16:45:01 +0000 (16:45 +0000)
lib/silcutil/silcstrutil.c
lib/silcutil/silcstrutil.h

index 8bec2fc7d54f99d0394f2a696471315bb7b3d912..db912fe3204b99ba3dcff8fedd3871760baf786e 100644 (file)
@@ -264,3 +264,52 @@ int silc_string_compare(char *string1, char *string2)
   silc_free(tmpstr2);
   return FALSE;
 }
+
+/* Splits a string containing separator `ch' and returns an array of the
+   splitted strings. */
+
+char **silc_string_split(const char *string, char ch, int *ret_count)
+{
+  char **splitted = NULL, sep[1], *item, *cp;
+  int i = 0, len;
+
+  if (!string)
+    return NULL;
+  if (!ret_count)
+    return NULL;
+
+  splitted = silc_calloc(1, sizeof(*splitted));
+  if (!splitted)
+    return NULL;
+
+  if (!strchr(string, ch)) {
+    splitted[0] = silc_memdup(string, strlen(string));
+    *ret_count = 1;
+    return splitted;
+  }
+
+  sep[0] = ch;
+  cp = (char *)string;
+  while(cp) {
+    len = strcspn(cp, sep);
+    item = silc_memdup(cp, len);
+    if (!item) {
+      silc_free(splitted);
+      return NULL;
+    }
+
+    cp += len;
+    if (strlen(cp) == 0)
+      cp = NULL;
+    else
+      cp++;
+
+    splitted = silc_realloc(splitted, (i + 1) * sizeof(*splitted));
+    if (!splitted)
+      return NULL;
+    splitted[i++] = item;
+  }
+  *ret_count = i;
+
+  return splitted;
+}
index c223fe6b7c6e3dbf6dcb11c46521f38a6c44a2a3..0e20e98f91a17ca4d6b65f9066861e18ff0ea78d 100644 (file)
@@ -190,4 +190,21 @@ int silc_string_match(const char *string1, const char *string2);
  ***/
 int silc_string_compare(char *string1, char *string2);
 
+/****f* silcutil/SilcStrUtilAPI/silc_string_split
+ *
+ * SYNOPSIS
+ *
+ *    char **silc_string_split(const char *string, char ch, int *ret_count);
+ *
+ * DESCRIPTION
+ *
+ *    Splits a `string' that has a separator `ch' into an array of strings
+ *    and returns the array.  The `ret_count' will contain the number of
+ *    strings in the array.  Caller must free the strings and the array.
+ *    Returns NULL on error.  If the string does not have `ch' separator
+ *    this returns the `string' in the array.
+ *
+ ***/
+char **silc_string_split(const char *string, char ch, int *ret_count);
+
 #endif /* SILCSTRUTIL_H */