Splitting string in C

Asked

Viewed 176 times

2

I am very beginner in C yet, but I have a lot of experience with python, I have a project that I need to receive from the user 3 numbers in the same line and make a vector with these 3 numbers

in the input digit

3 1 37

wanted it to form a vector [3,1,37] only one thing, the first (in this case the 3) can also be characters. something like

load 1 23 or delete 2 56

in python would be extremely simple, just received a string input and dps do an input=split.()

#include <stdio.h>
#include <string.h>C
int main ()
{
  char entrada[31];
  char * separado;
  gets(entrada);
  separado = strtok (entrada," ");
  while (separado != NULL)
  {
    printf ("%s\n",separado);
    separado = strtok (NULL, " ");
  }
  return 0;
}

I found this code in a gringo forum, someone knows if there is a simpler way or so explain to me how it works? I do not understand

  • 1

    Pertinent to your question, however you do not want split (split verb in English that means divide, separate) Oce needs concatenate data, that is, join 3 data passed by the user separated by comma in an array.

  • but it would be like splitting 1 string into 3

  • I understood, but where will the user pass these numbers, what is the origin of these 3 numbers? It comes direct from the terminal? If there are 3 numbers (3 distinct data) it is necessary a certain separator?

1 answer

2

Here is an example capable of converting a string containing space-separated data and aramazena it into a vector:

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


char ** strsplit( const char * src, const char * delim )
{
    char * pbuf = NULL;
    char * ptok = NULL;
    int count = 0;
    int srclen = 0;
    char ** pparr = NULL;

    srclen = strlen( src );

    pbuf = (char*) malloc( srclen + 1 );

    if( !pbuf )
        return NULL;

    strcpy( pbuf, src );

    ptok = strtok( pbuf, delim );

    while( ptok )
    {
        pparr = (char**) realloc( pparr, (count+1) * sizeof(char*) );
        *(pparr + count) = strdup(ptok);

        count++;
        ptok = strtok( NULL, delim );
    }

    pparr = (char**) realloc( pparr, (count+1) * sizeof(char*) );
    *(pparr + count) = NULL;

    free(pbuf);

    return pparr;
}


void strsplitfree( char ** strlist )
{
    int i = 0;

    while( strlist[i])
        free( strlist[i++] );

    free( strlist );
}


int main( int argc, char * argv[] )
{
    int i = 0;
    char ** vec = NULL;

    vec = strsplit( "3 pratos de trigo para 3 tigres tristes", " " );

    while( vec[i] )
    {
        printf("[%d] %s\n", i , vec[i] );
        i++;
    }

    strsplitfree( vec );

    return 0;
}

Exit:

$ ./teste 
[0] 3
[1] pratos
[2] de
[3] trigo
[4] para
[5] 3
[6] tigres
[7] tristes

Browser other questions tagged

You are not signed in. Login or sign up in order to post.