priyanka999kamlekar
asked on
strtok failing when word is empty in one of delemter
char myWords[100] = "asdlakm#asdasd##asdas#sas ";
char *temp;
temp = strtok(myWords, "#");
printf("1. %s\n", temp);
int i = 1;
while(temp)
{
temp = strtok(NULL, "#");
i++;
printf("%d. %s\n", i, temp);
}
out put:
1. asdlakm
2. asdasd
3. asdas
4. sas
5. (null)
Expected out put:
1. asdlakm
2. asdasd
3.
4. asdas
5. sas
Please let me know how to handle this type of issue. Here strtok is ignoring the # and returning the next work.
char *temp;
temp = strtok(myWords, "#");
printf("1. %s\n", temp);
int i = 1;
while(temp)
{
temp = strtok(NULL, "#");
i++;
printf("%d. %s\n", i, temp);
}
out put:
1. asdlakm
2. asdasd
3. asdas
4. sas
5. (null)
Expected out put:
1. asdlakm
2. asdasd
3.
4. asdas
5. sas
Please let me know how to handle this type of issue. Here strtok is ignoring the # and returning the next work.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
the strtok isn't intended to work the way you expect. It's functionality is to find tokens speparated by one or more characters of a set of delimiters, it's not intended to find the delimeters itself. So in your case there's no difference between "A#B" and "A###B" since it only contains two tokens. In fact it's good strtok works this way because this way you can i.e. skip multiple whitespaces by using delimiter like " \t".
IMO you should try to implement a loop to search for all '#' i.e. using strstr function instead.
ZOPPO