Deep breath, step backward. You have allinfo ="white, black, green,grey,blue" ;
and you want something like:
token[0] = "white";
token[1] = "black";
token[2] = "green";
// etc
Right? The string is to be broken apart into the pieces that are separated by the delimiter. Comma, in this case.
Yeah, this sort of thing sucks on a processor with drastically limited memory. The "algorithms" class I'm taking says that Java uses (2*N + 64) bytes to store an N-character string (this is desktop java, where a char is two bytes.) That's a lot of overhead! I assume that Arduino's String library is a little bit better, but it's still not going t be "good."
So let's use C's bare "char " structures instead; these are just pointers to arrays of characters, terminated with a null (by convention.) If we want to support, say, 20 tokens, we could have an array of 20 char pointers:char *tokens[20];
Note that this is just an array of pointers; it doesn't make any space for the characters themselves. There are a bunch of ways to set aside or allocate storage for the actual characters, but let's take the most efficient - we don't need to do anything because they are already in the string that we've read.
All we really need to do is replace all the commas (which terminate the tokens) with nulls (which terminate a C string), and keep track of where the next non-command character is. This is more or less what strtok does, but it's a bit funny. Something like:
int tokenize(char *s, char *tokens[], int maxtokens)
{
// Accept a string pointed to by s.
// update the list of comma-delimited tokens, replacing the commas with nulls.
// return the number of tokens found, not to exceed maxtokens.
// strtok does most of the work for us.
int i;
tokens[0] = strtok(s, ","); // first call is special
for (i=1; i < maxtokens; i++) {
tokens[i] = strtok(NULL, ",");
if (tokens[i] == NULL) {
break;
}
}
return i;
}
Here it is, wrapped in a test program (for unix-like systems) [EDIT: now, really!]
#include <stdio.h>
#include <string.h>
#define MAXTOKENS 20
char stuff[] = "white, black, green,grey,blue" ;
char *tokens[MAXTOKENS];
int tokenize(char *s, char *tokens[], int maxtokens)
{
// Accept a string pointed to by s.
// update the list of comma-delimited tokens, replacing the commas with nulls.
// return the number of tokens found, not to exceed maxtokens.
// strtok does most of the work for us.
int i;
tokens[0] = strtok(s, ","); // first call is special
for (i=1; i < maxtokens; i++) {
tokens[i] = strtok(NULL, ",");
if (tokens[i] == NULL) {
break;
}
}
return i;
}
int main()
{
int ntokens;
printf("Original String = %s\n", stuff);
ntokens = tokenize(stuff, tokens, MAXTOKENS);
printf("Parsed %d tokens\n", ntokens);
for (int i=0; i<ntokens; i++) {
printf("token %d = %s\n", i, tokens[i]);
}
}