String Scanning
One of the powerful features of Icon is string scanning. The scan string operator, ?
saves the current string scanning environment and creates a new string scanning environment. The string scanning environment consists of two keyword variables, &subject
and &pos
. Where &subject is the string being scanned, and &pos is the cursor or current position within the subject string.
For example
s := "this is a string" s ? write("subject= pos=")
would produce subject= pos=
Built-in and user defined functions can be used to move around within the string being scanned. Many of the built in functions will default to &subject and &pos (for example the find function). The following, for example, will write all blank delimited "words" in a string.
s := "this is a string" s ? { # Establish string scanning environment while not pos(0) do { # Test for end of string tab(many(' ')) # Skip past any blanks word := tab(upto(' ') | 0) # the next word is up to the next blank -or- the end of the line write(word) # write the word } }
A more complicated example demonstrates the integration of generators and string scanning within the language.
procedure main s := "Mon Dec 8" s ? write(Mdate | "not a valid date")
end
# Define a matching function that returns
# a string that matches a day month dayofmonth
procedure Mdate
# Define some initial values
static dates
static days
initial { days := dates := ["Jan","Feb","Mar","Apr","May","Jun", "Jul","Aug","Sep","Oct","Nov","Dec"]
}
every suspend (retval <- tab(match(!days)) || # Match a day =" " || # Followed by a blank tab(match(!dates)) || # Followed by the month =" " || # Followed by a blank matchdigits(2) # Followed by at least 2 digits ) & (=" " | pos(0) ) & # Either a blank or the end of the string retval # And finally return the string
end
# Matching function that returns a string of n digits
procedure matchdigits(n) suspend (v := tab(many(&digits)) & *v <= n) & v
end
The idiom of expr1 & expr2 & expr3
returns the value of the last expression
Read more about this topic: Icon (programming Language)
Famous quotes containing the word string:
“A culture may be conceived as a network of beliefs and purposes in which any string in the net pulls and is pulled by the others, thus perpetually changing the configuration of the whole. If the cultural element called morals takes on a new shape, we must ask what other strings have pulled it out of line. It cannot be one solitary string, nor even the strings nearby, for the network is three-dimensional at least.”
—Jacques Barzun (b. 1907)