I have a string which has been sent using udp. Now I want to read the string, tokenize it and save it to an char array. Only the first letter of each word is saved. So I just get 5 ‘e’s from element01 to element05. I’m working in Arduino, and I know some c# but no c or c++.
//p_params->packetBuffer contains the following string:
//element01#element02#element03#element04#element05
void packtStriper( receivedPacket * p_params )
{
char delims[] = "#";
char *result = NULL;
int i = 0;
//Tokenize string - 'split' it on hash mark
result = strtok( p_params->packetBuffer, delims );
//Iterate through the tokens and save them to my list
while( result != NULL )
{
p_params->listData[i] = *result;
i++;
result = strtok( NULL, delims );
}
//Display the data just received
for(int j =0; j<i; j++)
{
Serial.print( "Data " );
Serial.print( j );
Serial.print( ": " );
Serial.println( p_params->listData[j] );
}
}
typedef struct receivedPacket
{
char * REQType;
char * confName;
unsigned int confData[64];
char listData[10];
char packetBuffer[UDP_BUFFER_SIZE];
int packetSize;
int inProduction;
}receivedPacket;
Since the following code prints the full element names I thought I could use just result. But this also return an error.
char str[] = "element01#element02#element03#element04#element05";
char delims[] = "#";
char *result = NULL;
result = strtok( str, delims );
while( result != NULL ) {
printf( "result is \"%s\"\n", result );
result = strtok( NULL, delims );
}
The following line:
takes the first char of
result, and copies it to theith char ofp_params->listData. So only the first char of each token is copied. How do you expect to get those tokens, as one sequence of element01element02element03element04element05, or as an array of strings?Bear in mind that in C and C++, an array of chars holds only one string, simply put. To hold more than one string, you need an array of array of chars, or some delimiter (which is where you’ve started…).
Edit:
Given you want to get an array of strings, you can use the following: declare
listDataaswhich means
listDatacan now hold up to 10 strings. Then, instead of assigning*resulttolistData[i], use the following:which will create a copy of the string, and store it in the next entry.
Note:
strdupallocates memory for you. You mustfree()those strings when you’re done with them.listDatacan only hold up to 10 strings. You should at least make sureidoesn’t get over 9 in thewhileor so.