18 February 2011

stringutil: my c library for string utilities

Hello,

I am working on some task in CGI, I'll try to write some string utility functions to help me simplify task..

this lib is still simple, It just contains 1 non-static function `split`

#ifndef _STRING_UTIL_
#define _STRING_UTIL_

static size_t count(const char*, char);
size_t split(const char *const, const char*, char***);

#endif


#include <string.h>
#include <stdlib.h>
#include "stringutil.h"

static size_t count(const char *str, char ch)
{
    if (str == NULL) return 0;
    size_t count = 1;
    while (*str)
        if (*str++ == ch) count++;
    return count;
}

size_t split(const char *const str, const char* delim, char ***out)
{
    size_t size = count(str, *delim);
    *out = calloc(size, sizeof(char));
    char* token = NULL;
    char* tmp = (char*) str;
    int i=0;
    while ((token = strtok(tmp, delim)) != NULL)
    {
        tmp = NULL;
        (*out)[i] = (char*) malloc(sizeof strlen(token) * 4 /* to solve some bug */);
        strcpy((*out)[i++], token);
    }
    return size;
}

Post a Comment