|
|
|
Analyzing Strings with sscanfThe counterpart or "opposite" of sprintf is sscanf. It looks at a string, and extracts values from it according to another string with format specifiers. It then places the values it has extracted in its arguments. The arguments must be variables, or other things that you can assign values to. For example, after the following code segment, the variable f will contain -3.6, and the variable i will contain 17: float f; int i; string the_string = "foo -3.6 fum dum 17"; sscanf(the_string, "foo %f fum dum %d", f, i); Note that sscanf isn't an ordinary method or built-in function, but a very special construction in Pike. The reason is that sscanf has to change its arguments, and since Pike uses call-by-value, no ordinary method or built-in function can do that. The format string consists of characters, that should match the contents of the first string exactly. Blanks are significant. For example, the part fum dum in the format string must match a part of the analyzed string (the_string) exactly. The format string can also contain "percent specifiers", which match various things. For example, %d us used to match an integer. Here is a list of format specifiers:
If an asterisk (*) is put between the percent and the operator, e. g. %*d, the operator will only match its argument, and not assign any variables. sscanf returns the number of percent specifiers that were successfully matched. The matching done by sscanf is rather simple-minded. It looks at the format string up to the next %, and tries to match that with the analyzed string. If successful, it then goes on to the next part of the format string. If a part of the format string does not match, sscanf immediately returns (with the number of percent specifiers that were successfully matched). Variables in the argument list that correspond to percent specifiers that were not successfully matched will not be changed. Some examples of sscanf:
A feature with sscanf is that you can define variables inside it: sscanf("foo % 1 2 3 fum", "%s %% %{%d%} %s", string s1, array(string) a, string s2); In contrast to variables defined in a for statement, these variables are available in the rest of the block, and not just inside the sscanf. |
|||||||||||||||||||||||||||||||||||||