iaacp
iaacp

Reputation: 4835

Tokenizing a string in C using strtok()

I'm trying to write a function that takes an HTTP request and extracts a small amount of the data. My function looks like this:

char* handle_request(char * req) {
    char * ftoken; // this will be a token that we pull out of the 'path' variable 
    // for example, in req (below), this will be "f=fib"
    char * atoken; // A token representing the argument to the function, i.e., "n=10"     
        ...

    // Need to set the 'ftoken' variable to the first arg of the path variable.
    // Use the strtok function to do this
    ftoken = strtok(req, "&");
    printf("ftoken = %s", ftoken);

    // TODO: set atoken to the n= argument;
    atoken = strtok(NULL, "");
    printf("atoken = %s", atoken);
   }

req will usually look something like this: GET /?f=fib&n=10 HTTP/1.1

Currently, after calling strtok(), ftoken prints out as GET /?f=fibGET /favicon.ico HTTP/1.1 which is obviously wrong. Ideally, it would be f=fib and atoken would be n=10 Can anyone help me figure this out please?

Upvotes: 1

Views: 1017

Answers (2)

Fe2O3
Fe2O3

Reputation: 8344

Given the sample string (req): "GET /?f=fib&n=10 HTTP/1.1", and your wish to extract "f=fib" and "n=10", try this...

char *sepChars = " /?&";
char *discard = strtok( req, sepChars );
char *ftoken = strtok( NULL, sepChars );
char *atoken = strtok( NULL, sepChars );

Upvotes: 0

fatrock92
fatrock92

Reputation: 837

Input -> GET /?f=fib&n=10 HTTP/1.1

Output -> ftoken f=fib and atoken 10

Code ->

ftoken = strtok(req, "?"); // This tokenizes the string till ?
ftoken = strtok(NULL, "&"); // This tokenizes the string till & 
                            // and stores the results in ftoken
printf("ftoken = %s", ftoken); // Result should be -> 'f=fib'

atoken = strtok(NULL, "="); // This tokenizes the string till =.
atoken = strtok(NULL, " "); // This tokenizes the string till next space.
printf("atoken = %s", atoken); // Result should be -> 'n=10'

Upvotes: 1

Related Questions