Receive only one token from strtok at a time
Consider the following scenario with two different lines:
Row1: MyID-MyName-MyAddress-MyNumber-MyNumber2-MyAlias
Row2: MyID-MyName-MyAddress-MyNumber--MyAlias
The second example is missing a value MyNumber2
. I need to extract each attribute using strtok()
. So far this is my code:
MyID = strtok (str, "-"); //where 'str' is the full string
MyName = strtok (NULL, "-");
MyAddress = strtok (NULL, "-");
MyNumber = strtok (NULL, "-");
MyNumber2 = strtok (NULL, "-");
MyAlias = strtok (NULL, "-");
The first example works well and I can store each attribute inside variables. However, in the second example I am having problems:
When entering a variable MyNumber2
, it strtok()
does not return an empty string (as I would like). Instead, it reads the string until the first character matches the delimiter "-"
, thus ignoring the existence of a null value in the string.
Is it possible to split a string just once per delimiter?
source to share
I think you should use a standard function strchr
. for example
#include <stdio.h>
#include <string.h>
int main( void )
{
char s[] = "MyID-MyName-MyAddress-MyNumber--MyAlias";
for ( char *p = s, *q = s; p != NULL; p = q )
{
q = strchr( p, '-' );
if ( q )
{
printf( "\"%*.*s\"\n", ( int )(q - p ), ( int )( q - p ), p );
++q;
}
else
{
printf( "\"%s\"\n", p );
}
}
}
Program output
"MyID"
"MyName"
"MyAddress"
"MyNumber"
""
"MyAlias"
source to share
Strtok
can not tokenize empty values ββbetween delimiters. To find out the reason, Please check the first answer here
I was in the same situation as you. I used strstr
to do the same as below:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main(void)
{
char str[] = "MyID-MyName-MyAddress-MyNumber--MyAlias";
char * str1, * token;
int i = 0;
int parsed_buffer_length = 0;
char * previous_delimiter_index = str;
char * delimiter_index = str;
for(;;)
{
str1 = str+parsed_buffer_length;
delimiter_index = strstr(str1,"-");
if(delimiter_index==NULL)
{
printf("%s",str1); //prints last token
break;
}
token = malloc(delimiter_index-previous_delimiter_index+1);
memset(token,'\0',delimiter_index-previous_delimiter_index+1));
strncpy(token,str1,(delimiter_index-previous_delimiter_index));
printf("%s\n",token);
parsed_buffer_length = (int)(parsed_buffer_length+delimiter_index-previous_delimiter_index+1);
previous_delimiter_index = delimiter_index+1;
free(token);
}
}
Which gives the result:
MyID
MyName
MyAddress
MyNumbers
MyAlias
source to share