uf_user
uf_user

Reputation: 27

Splitting a string based on delimiter in C

I have a set of lines in a file and each line have several strings seperated by ",".

How can I split the string based on the delimiter and store the results in a multidimensional array where the first index is the row number in the input file and the second is the column number?

Upvotes: 0

Views: 485

Answers (2)

KrisSodroski
KrisSodroski

Reputation: 2842

Use strtok() in string.h header file can be used in C.

strtok(char * array, ",");


char * array[size of columns][size of rows]
pch = strtok (str,",");
int i, j;
while (pch != NULL)
{
  array[i++][j] = pch;
  if( i == size of columns - 1){
    i = 0; j++;
  } 
  pch = strtok (NULL, ",");

  if(j == size of rows -1){
    break;
  }
}

Upvotes: 3

Jesus Ramos
Jesus Ramos

Reputation: 23268

What you can do (because of the way c-strings work) is check characters until you encounter a "," then you replace that character with \0 (NULL character) and keep track of the last position you started checking at (either the beginning of the string or the character after the last NULL character. This will give you usable c-strings of each delimited piece.

Upvotes: 1

Related Questions