Using sscanf to Extract Strings
Consider the problem of taking a string of the form;
and extracting the name "Bill" and the nickname "turtle.
Consider the following code (which works). The numbers are not really
part of the code. Rather, they are references in the discussion.
char line, s1, s2, s3, s4, s5, s6;
strcpy(line, "a MyArr[Bill]=/turtle/");
sscanf(line, "%s %[^\%[\%[a-z,A-Z]%[\]=/]%[^/]",
1 2 3 4 5 6
s1, s2, s3, s4, s5, s6);
- 1. It is clear that s1 will be "a". The form of the format specifer
is the familiar space.
- 2. The [^...] indicates the string can contain any character up to
the character or characters specified at the dots. In this case, the
specified character is '['. However as [ has special meaning, it is
indicated as '\['. Thus, in this case MyArr is written to string s2.
- 3. The [...] indicates the string can contain only the characters at
the dots. In this case the specified character is ']'. As it is a
special character, it is specified as '\['. Thus, '[' is written to s3.
- 4. The [a-z,A-Z] indicates the string can only contain these
alphabetical characters. Thus "Bill" is written to s4.
- 5. The [\]=/] indicates that the string can only contain the
characters ']', '=' and '/'. Thus, "]=/" is written to s5.
- 6. The [^/] indicates the string can contain any character other than
'/'. Thus, "turtle" is written to string s6.
It is best to use these concepts and then use trial and error, observing
the results using the debugger.