Need some advice on my Implementation of strsplit() using C


 
Thread Tools Search this Thread
Top Forums Programming Need some advice on my Implementation of strsplit() using C
# 1  
Old 05-18-2011
Tools Need some advice on my Implementation of strsplit() using C

I write a strsplit function which converts a string separated by a delimeter to a sub-string array.

If anyone can give some advice to optimize it, or raise some new thought about this implementation? Tkx.

Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

char * const *strsplit(char *p, char sep)
{

        if (p == NULL)
                return NULL;

        int num = 0;
        int i = 0;
        char **arry = NULL;
        char **newarrybuff;
        char *strcur;
        char *tmpstr = malloc(strlen(p) + 1);

        if (!tmpstr)
                return NULL;
        strcur = tmpstr;
        strcpy(tmpstr, p);

        while (strcur) {
                if (*strcur == sep) {
                        strcur++;
                        continue;
                }
                newarrybuff = realloc(arry, sizeof(char*) * (i+1));
                if (!newarrybuff) {
                        free(arry);
                        return NULL;
                }
                arry = newarrybuff;
                arry[i++] = strcur;
             
                strcur = strchr(strcur, sep);
                if(strcur)
                        *strcur++ = '\0';
        }
         newarrybuff = realloc(arry, sizeof(char*) * (i+1));
         if (!newarrybuff) {
                 free(arry);
                 return NULL;
         }
         arry = newarrybuff;
         arry[i++] = NULL;

         newarrybuff = realloc(arry, sizeof(char*) * (i+1));
         if (!newarrybuff) {
                 free(arry);
                 return NULL;
         }
         arry = newarrybuff;
         arry[i++] = tmpstr;

         return arry;
}

void strsplitfree(char * const *p)
{
        if (!p) return;

        char * const *tmp = p;
        while (*tmp++);
        free(*tmp);
        free((void*)p);
}

int main(int argc, char **argv)
{
        char str[] = "::::hello::wold:";
        char * const *s = strsplit(str, ':');
        int j=0;
        if (s == NULL)
                return 1;
        for (j = 0; s[j] != NULL; j++) {
                printf("%s\n", s[j]);
        }

        strsplitfree(s);
        return 0;
}


Last edited by vistastar; 05-18-2011 at 10:02 AM..
# 2  
Old 05-18-2011
First, use strdup() to duplicate a string on the heap.

Second, don't duplicate each and every substring - duplicate the entire string and just split it by replacing the separators with NULs, filling in your pointer array as you go. (Yes, it's spelled "NUL". That's the '\0' character.)

Something like this:

Code:
#include <string.h>
#include <strings.h>
#include <stdio.h>
#include <stdlib.h>

char **strsplit( const char *str, char sep )
{
    char *pp;
    char *qq;
    unsigned int sepCount;

    char *newStr = strdup( str );

    // count the separators
    for ( pp = newStr, sepCount = 0; *pp; pp++ )
    {
         if ( sep == *pp ) sepCount++;
    }

    // N separators means N + 1 strings, plus we need
    // a NULL terminator at the end of the pointer array
    char **result = calloc( 2 + sepCount, sizeof( *result ) );

    // first result is the start of the original string
    result[ 0 ] = newStr;

    // now split the string by inserting NUL characters
    // in place of separators, and filling in the pointer
    // array as we go
    pp = newStr;
    sepCount = 1;
    for ( ;; )
    {
        // find the next separator
        qq = strchr( pp, sep );
        if ( NULL == qq ) break;

        // replace it to split the string
        *qq = '\0';

        // point at the start of the next sting
        pp = qq + 1;

        // fill in the array with the next string
        result[ sepCount ] = pp;

        sepCount++;
    }

    return( result );
}

void freesplit( char **split )
{
    free( split[ 0 ] );
    free( split );
}

int main( int argc, char **argv )
{
    char **split;

    int ii;
    int jj;

    for ( ii = 1; ii < argc; ii++ )
    {
        split = strsplit( argv[ ii ], ':' );
        for ( jj = 0; split[ jj ]; jj++ )
        {
            printf( "string[ %d ] = '%s'\n", jj, split[ jj ] );
        }

        freesplit( split );
    }

    return( 0 );
}

# 3  
Old 05-18-2011
Here is an old utility. It splits string from the command line, it also has extra stuff you should probably ignore: parsing options, formatting output.
There are two files:

ssplit.c
classes.c

make:
Code:
[g]cc classes.c ssplit.c -o ssplit

# 4  
Old 05-19-2011
1, Why must use strdup but malloc and strcpy?
2, Indeed I duplicate the entire string.
3, Is calloc better than malloc?
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Programming

C: CSV implementation

I have this code from a programming book: #include <stdio.h> #include <string.h> char buf; /* input line buffer */ char* field; /* fields */ char* unquote( char* ); /* csvgetline: read and parse line, return field count */ /* sample input:... (3 Replies)
Discussion started by: totoro125
3 Replies

2. Shell Programming and Scripting

Back up implementation

Is there any command to take create back up of a file as soon as when it is created?If not is it possible to create something like that? (3 Replies)
Discussion started by: Sindhu R
3 Replies

3. UNIX for Dummies Questions & Answers

Lseek implementation

Hi everybody, i've been googling for ages now and gotten kinda desperate... The question, however, might be rather trivial for the experts: What is it exactly, i.e. physically, the POSIX function (for a file) "lseek" does? Does it trigger some kind of synchronization on disk? Is it just for the... (4 Replies)
Discussion started by: Humudituu
4 Replies

4. Linux

CAPWAP implementation

Hi I'm trying to implement CAPWAP protocol for my application.i'm able to configure my server side but i'm getting error at client(WTP) side as IOCTL error.while running the command #./WTP /mnt/cf/capwap/ : wlan2 Starting WTP... # WTP Loads... (0 Replies)
Discussion started by: ran789
0 Replies

5. Programming

Implementation of dup2

Hi all,I'm reading <Advanced programming in the UNIX environment>,that book asked the reader to implement a function which has same functions with dup2 without calling fcntl.Could anyone give me a tip?Any help will be appreciated.:) (8 Replies)
Discussion started by: homeboy
8 Replies

6. UNIX for Advanced & Expert Users

Malloc Implementation in C

Hey Guys Some of my friends have got together and we are trying to write a basic kernel similar to Linux. I am trying to implement the malloc function in C and I am using a doubly linked list as the primary data structure. I need to allocate memory for this link list (duh...) and I don't feel... (2 Replies)
Discussion started by: rbansal2
2 Replies

7. Programming

Malloc implementation in C

Hey Guys I am trying to implement the malloc function for my OS class and I am having a little trouble with it. I would be really grateful if I could get some hints on this problem. So I am using a doubly-linked list as my data structure and I have to allocate memory for it (duh...). The... (1 Reply)
Discussion started by: Gambit_b
1 Replies

8. Shell Programming and Scripting

Need help on AWK implementation

Hi, I am accepting a string from user. compare this output with the awk output as below... echo "\n\n\tDay : \c" read day awk '{ if($day == $2) { if ($mon == $1) { print "Yes" }}}' syslog.txt I am getting the follwoing error awk: Field $() is not correct. The input line... (5 Replies)
Discussion started by: EmbedUX
5 Replies

9. UNIX for Advanced & Expert Users

Implementation of ls - i command

It is possible for me to obtain the Inode of the path name using ls -i <pathname> command Can anyone tell me how its implemented... (3 Replies)
Discussion started by: ganapathy.psgit
3 Replies

10. UNIX for Dummies Questions & Answers

Shell Implementation

I want to implement my own simple multi tasking shell in Unix which will take care of redirection (<, >, >>) and piping. I am just unable to get a concrete idea of how exactly I have to start. I have several books...some are.. 1. Maurice Bach- Design Of Unix Operating System 2. Richard... (3 Replies)
Discussion started by: clickonline1
3 Replies
Login or Register to Ask a Question