Strtok(), no token match
Asked Answered
O

2

6

I was trying to parse strings using strtok(); I am trying to parse strings delimited by a semicolon ( ; ). But when I input a string with no semicolons to strtok(), it returns the entire string. Shouldn't it be returning NULL if there are no token matches?

This is my code:

int main(int argc, char** argv) 
{
    char cmd[] = "INSERT A->B B->C INSERT C->D";
    char delim[] = ";";
    char *result = NULL;

    result = strtok(cmd,delim);

    if(result == NULL)
    {
        printf("\n NO TOKENS\n");
    }
    else
    {

        printf("\nWe got something !! %s ",result);

    }

    return (EXIT_SUCCESS);
}

The output is : We got something !! INSERT A->B B->C INSERT C->D

Offcenter answered 29/11, 2012 at 19:52 Comment(2)
shouldn't it be returning NULL if there are no token matches ? No. The entire string is a token match.Abbreviate
If you're searching for ';' rather than tokens, try strchr.Rosalbarosalee
C
9

No, the delimiter means that it's the thing that separates tokens, so if there is no delimiters, then the entire string is considered the first token

consider if you have two tokens, then take one of those tokens away. if you have

a;b

then you have tokens a and b

now if you take b away...

a

you still have token a

Colonial answered 29/11, 2012 at 20:0 Comment(0)
I
0

If you read the man page(http://man7.org/linux/man-pages/man3/strtok.3.html) carefully, you will see that it says:

The strtok() function breaks a string into a sequence of zero or more nonempty tokens.

So, basically it is either breaking your input string into multiple tokens or not(and it happens when it finds no given delimiter into the given string).

Example:

input_string || delimiter || tokens

"abc:def" || ":" || "abc" and "def"

"abcdef" || ":" || "abcdef"

Integumentary answered 25/10, 2019 at 19:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.