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?

2
  • C++ Solution: How can I split a string by a delimiter into an array? Commented Jul 30, 2013 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. Commented Jul 30, 2013 at 20:41

2 Answers 2

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;
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Can someone provide me with some sort of pseudocode,I am new to pointers and getting confused with the multidimensional array thing
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.

5 Comments

Requires two passes over the entire string as opposed to one.
So you want to walk over every character then?
@Magn3s1um If you keep the last non null character you found stored you don't need to walk the string twice. Also strtok() does almost the same internally.
So then why not use strtok()?
@Magn3s1um Indirect function calls through pointers can be slow if it happens that the string being looked at is long.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.