Link to home
Start Free TrialLog in
Avatar of bachra04
bachra04Flag for Canada

asked on

remove a token in c programming

This one is a little bit more complex than the last question :

char str[] ="<1.2.3.4:4747>;+instance=45;+gks=uuu.";

I want to remove one token only when it starts with +instance

i.e.

Entry:

"<1.2.3.4:4747>;+instance=45;+gks=uuu."

output:

"<1.2.3.4:4747>;+gks=uuu."

ideally I will do the removal on the buffer itself without copying to another buffer,
Is that possible ?
Avatar of phoffric
phoffric

strstr can be used to point to the start of the +instance string (returns, say pointer p0).
   http://www.cplusplus.com/reference/cstring/strstr/

Looks like the ; is your sentinel and you want to keep it.
I assume that ; is not part of the token you want to replace.
Then, you can use strchr to find the ; (returns, say pointer p1).
   http://www.cplusplus.com/reference/cstring/strchr/

strcpy( p0, p1) should copy the ; and beyond over the token starting at p0 - including the terminating null byte.
    http://www.cplusplus.com/reference/cstring/strcpy/
By reviewing the error return values from strstr and strchr, you can add error checking to verify that you have the +instance string token, and the ; that you expect to follow.
It's actually even easier than your last question, and yes, it can be done in the one buffer, e.g.

#include <string.h>

int remove_token(char* buf, const char* token, const char delim) {

    int idx = 0;
    char* delimpos = NULL;
    char* tokenpos = strstr(buf, token);

    if (!tokenpos) return -1; // token not found

    ixd = (int) tokenpos - buf;
    delimpos = strchr(buf + idx,delim);

    if (!delimpos) {
        buf[idx] = '\0';  // no following delimiter, cut of '+instance='

        return strlen(buf); // or just '1', as you like
    }
    
    strcpy(tokenpos, delimpos + 1); // copy the rest to the end of where the token was

    return strlen(buf); // or just '1', as you like
}

int main () {

    char str[] ="<1.2.3.4:4747>;+instance=45;+gks=uuu.";

    remove_token(str, "+instance", ';');
}

Open in new window

SOLUTION
Avatar of phoffric
phoffric

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bachra04

ASKER

I think there is a bug when the input buffer has a long sentence with carriage return e,g.
<1.2.3.4:4747>;+instance=45;+gks=uuu.\r\n
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n
yyyyyyyyyyyyyyy\r\n

Etc ...

I m seeing some ovelap at the end , do you know the reason ?
This is for JKr solution.  I will try phoffric solution as well.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial