Suppose I have to split a string into words, (ie "I am Mamun") [here the SPACES ARE NOT EQUAL] I have used 1 space as delimiter in strtok function but got wrong output. Someone please explain this :(
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="# Timestep No_Moles No_Specs CO3 CO2 HO CHO2 O CHO3";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," #");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " #");
}
return 0;
}
my code : http://codepad.org/eRwUDkVh
The problem isn't the different numbers of spaces, it's that the later fields are delimited by a tab not a space. So simply changing
pch = strtok (NULL, " #");
to
pch = strtok (NULL, " \t#");
^^
solves the problem.
You have tabs in your string not just spaces. To split properly based on spaces and tabs you should put character \\t
into the input of strtok
too.
pch = strtok (NULL, " \t#");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.