bachra04
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=u uu.";
I want to remove one token only when it starts with +instance
i.e.
Entry:
"<1.2.3.4:4747>;+instance= 45;+gks=uu u."
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 ?
char str[] ="<1.2.3.4:4747>;+instance
I want to remove one token only when it starts with +instance
i.e.
Entry:
"<1.2.3.4:4747>;+instance=
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 ?
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", ';');
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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=4 5;+gks=uuu .\r\n
xxxxxxxxxxxxxxxxxxxxxxxxxx xxxxx\r\n
yyyyyyyyyyyyyyy\r\n
Etc ...
I m seeing some ovelap at the end , do you know the reason ?
<1.2.3.4:4747>;+instance=4
xxxxxxxxxxxxxxxxxxxxxxxxxx
yyyyyyyyyyyyyyy\r\n
Etc ...
I m seeing some ovelap at the end , do you know the reason ?
ASKER
This is for JKr solution. I will try phoffric solution as well.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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/