Split string with delimiters in C

前端 未结 20 1392
你的背包
你的背包 2020-11-21 11:56

How do I write a function to split and return an array for a string with delimiters in the C programming language?

char* str = \"JAN,FEB,MAR,APR,MAY,JUN,JUL,         


        
20条回答
  •  攒了一身酷
    2020-11-21 12:22

    In the above example, there would be a way to return an array of null terminated strings (like you want) in place in the string. It would not make it possible to pass a literal string though, as it would have to be modified by the function:

    #include 
    #include 
    #include 
    
    char** str_split( char* str, char delim, int* numSplits )
    {
        char** ret;
        int retLen;
        char* c;
    
        if ( ( str == NULL ) ||
            ( delim == '\0' ) )
        {
            /* Either of those will cause problems */
            ret = NULL;
            retLen = -1;
        }
        else
        {
            retLen = 0;
            c = str;
    
            /* Pre-calculate number of elements */
            do
            {
                if ( *c == delim )
                {
                    retLen++;
                }
    
                c++;
            } while ( *c != '\0' );
    
            ret = malloc( ( retLen + 1 ) * sizeof( *ret ) );
            ret[retLen] = NULL;
    
            c = str;
            retLen = 1;
            ret[0] = str;
    
            do
            {
                if ( *c == delim )
                {
                    ret[retLen++] = &c[1];
                    *c = '\0';
                }
    
                c++;
            } while ( *c != '\0' );
        }
    
        if ( numSplits != NULL )
        {
            *numSplits = retLen;
        }
    
        return ret;
    }
    
    int main( int argc, char* argv[] )
    {
        const char* str = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
    
        char* strCpy;
        char** split;
        int num;
        int i;
    
        strCpy = malloc( strlen( str ) * sizeof( *strCpy ) );
        strcpy( strCpy, str );
    
        split = str_split( strCpy, ',', &num );
    
        if ( split == NULL )
        {
            puts( "str_split returned NULL" );
        }
        else
        {
            printf( "%i Results: \n", num );
    
            for ( i = 0; i < num; i++ )
            {
                puts( split[i] );
            }
        }
    
        free( split );
        free( strCpy );
    
        return 0;
    }
    

    There is probably a neater way to do it, but you get the idea.

提交回复
热议问题