0

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?

BlackVegetable
  • 12,594
  • 8
  • 50
  • 82
uf_user
  • 29
  • 9
  • C++ Solution: [How can I split a string by a delimiter into an array?](http://stackoverflow.com/questions/890164/how-can-i-split-a-string-by-a-delimiter-into-an-array) – Grijesh Chauhan Jul 30 '13 at 20:39
  • Sounds like this is what is known as a CSV file? You could look for CSV parsing code in C. I'm sure there are plenty of examples of that. – Tim B Jul 30 '13 at 20:41

2 Answers2

3

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;
  }
}
KrisSodroski
  • 2,796
  • 3
  • 24
  • 39
  • 3
    You should Complete your answer, OP need an array of strings, additionally add important note : `strtok() function modify the original input strings (first argument) by replacing delimiters with '\0' symbols.` So first argument can't be string literal. – Grijesh Chauhan Jul 30 '13 at 20:31
  • Can someone provide me with some sort of pseudocode,I am new to pointers and getting confused with the multidimensional array thing – uf_user Jul 30 '13 at 20:43
1

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.

Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88