Reputation: 136
Is there a way to use a string as a delimiter? We can use characters as delimiters using sscanf();
Example
I have
char url[]="username=jack&pwd=jack123&[email protected]"
i can use.
char username[100],pwd[100],email[100];
sscanf(url, "username=%[^&]&pwd=%[^&]&email=%[^\n]", username,pwd,email);
it works fine for this string. but for
url="username=jack&jill&pwd=jack&123&[email protected]"
it cant be used...its to remove SQL injection...but i want learn a trick to use &pwd,&email as delimiters..not necessarily with sscanf. Update: Solution doesnt necessarily need to be in C language. I only want to know of a way to use string as a delimiter
Upvotes: 0
Views: 293
Reputation: 1
Just code your own parsing. In many cases, representing in memory the AST you have parsed is useful. But do specify and document your input language (perhaps using EBNF notation).
Your input language (which you have not defined in your question) seems to be similar to the MIME type application/x-www-form-urlencoded
used in HTTP POST requests. So you might look, at least for inspiration, into the source code of free software libraries related to HTTP server processing (like libonion) and HTTP client processing (like libcurl).
You could read an entire line with getline
(or perhaps fgets
) then parse it appropriately. sscanf
with %n
, or strtok
might be useful, but you can also parse the line "manually" (consider using e.g. your recursive descent parser). You might use strchr
or strstr
also.
BTW, in many cases, using common textual representations like JSON, YAML, XML can be helpful, and you can easily find many libraries to handle them.
Notice also that strings can be processed as FILE*
by using fmemopen
and/or open_memstream
.
You could use parser generators such as bison (with flex).
In some cases, regular expressions could be useful. See regcomp and friends.
So what you want to achieve is quite easy to do and standard practice. But you need more that just sscanf
and you may want to combine several things.
Many external libraries (e.g. glib from GTK) provide some parsing. And you should care about UTF-8 (today, you have UTF-8 everywhere).
On Linux, if permitted to do so, you might use GNU readline instead of getline
when you want interactive input (with editing abilities and autocompletion). Then take inspiration from the source code of GNU bash (or of RefPerSys, if interested by C++).
If you are unfamiliar with usual parsing techniques, read a good book such as the Dragon Book. Most large programs deal somewhere with parsing, so you need to know how that can be done.
Upvotes: 2