0

So does this code adequately satisfy this question?

Write a function named tokenize() that will receive the following parameters: a char * to the string to tokenize, and a char * [] that will receive pointers to all of the tokens generated, in their order of generation. The function will return the number of tokens found in the string provided. The variable names you choose matter.

int tokenize (char * array, char * results[])
{
	int count;
	
	while (strlen(array))
	{
		count = 0;
		
		if(results[0] = strtok(array, "\t"))
			count++;
		while (results[count] = strtok(NULL, "\t"))
			count++;
	}
	
	return count;
}
2
Contributors
1
Reply
3
Views
6 Years
Discussion Span
Last Post by Ancient Dragon
0

line 5: when using strtok you don't need the length of the string. You have to call strtok() once before the loop, the first parameter is array and the second parameter is " " (one space), assuming tokens are separated with spaces. If they are separated by some other character, such as tabs, then use "\t".

So the program will be somethin like this:

char *sptr = strtok(array, " ");
while( sptr != NULL)
{

   // do something with this token

   // now get anoter token
   sptr = strtok(NULL, " ");
};

If you want to use both spaces and tabs as tokens, then use " \t", and strtok() will use either one.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.