View Full Version : please help with extraction of command from double qoutes
mile1982
10-21-2004, 08:50 AM
hey
i want to extract an argument from double qoutes, eg: when the user enters:
prompt "mile"
i need to extract everything within the double quotes, in my case, mile, and save it to a string. feedback/code would be appreciated
thanks
mile1982
RobSeace
10-21-2004, 01:08 PM
I'm not sure what the problem is... What's so difficult about doing
such a thing?? It's really rather simple:
char *parse_token (char *str, char **endp)
{
char *beg, *end, ch;
for (beg = str; *beg && isspace (*beg); beg++)
;
if ((*beg == '"') || (*beg == '\'')) {
ch = *beg++;
} else {
ch = '\0';
}
for (end = beg; *end; end++) {
if (ch == '\0') { /* just parsing whitespace-delimited token */
if (isspace (*end)) {
ch = *end;
break;
}
} else if (*end == ch) { /* parsing quoted token */
break;
}
}
if (*end != ch)
return (NULL); /* error: mismatched quotes */
if (*end) *end++ = '\0';
if (endp) *endp = end;
return (beg);
}
Now, that's all just quick and dirty, and off the top of my head,
completely untested... But, I think you should get the picture,
anyway... It's really not difficult to do... You might also want to
add handling for backslash-escaped quote chars inside the
quoted tokens... Hopefully, it's fairly obvious what you'd need to
change to make that happen...
int getString(char *text, char *target)
{
char *anf=strchr(text,'"');
if(anf==0) return -1; // error, no " found
anf++; // text starts one behind the "
char *end=strchr(anf,'"');
if(end==0) return -1; // error, no second " found
memcpy(target,anf,end-anf);
target[end-anf]=0;
return end-anf;
}
The strchr() command looks for the first time the specified char appears in
a string and delivers a pointer to this char back. So to get the real start
who have to add 1 to get the real first char. In theory you'd also have to
sub 1 from the end, but as you then would have to add 1 again to get the
right length I skipped that. This code returns -1 on error, else the length of
the extracted string.
You should pass the maximum fitting string length also to the function and
test before the copy if the length fits in it.
vBulletin® v3.7.4, Copyright ©2000-2009, Jelsoft Enterprises Ltd.