Searching and Reading Strings
Functions like
Read and
Find are most often used for processing text and data from external files. In some cases, however, you may find it convenient to use these same functions to process strings within
Mathematica. You can do this by using the function
StringToStream, which opens an input stream that takes characters not from an external file, but instead from a
Mathematica string.
| StringToStream["string"] | open an input stream for reading from a string |
| Close[stream] | close an input stream |
Treating strings as input streams.
This opens an input stream for reading from the string.
| Out[1]= |  |
|
This reads the first "word" from the string.
| Out[2]= |  |
|
This reads the remaining words from the string.
| Out[3]= |  |
|
This closes the input stream.
| Out[4]= |  |
|
Input streams associated with strings work just like those with files. At any given time, there is a current position in the stream, which advances when you use functions like
Read. The current position is given as the number of characters from the beginning of the string by the function
StreamPosition[stream]. You can explicitly set the current position using
SetStreamPosition[stream, n].
Here is an input stream associated with a string.
| Out[5]= |  |
|
The current position is initially 0 characters from the beginning of the string.
| Out[6]= |  |
|
This reads a number from the stream.
| Out[7]= |  |
|
The current position is now 3 characters from the beginning of the string.
| Out[8]= |  |
|
This sets the current position to be 1 character from the beginning of the string.
| Out[9]= |  |
|
If you now read a number from the string, you get the 23 part of 123.
| Out[10]= |  |
|
This sets the current position to the end of the string.
| Out[11]= |  |
|
If you now try to read from the stream, you will always get EndOfFile.
| Out[12]= |  |
|
| Out[13]= |  |
|
Particularly when you are processing large volumes of textual data, it is common to read fairly long strings into
Mathematica, then to use
StringToStream to allow further processing of these strings within
Mathematica. Once you have created an input stream using
StringToStream, you can read and search the string using any of the functions discussed for files.
This puts the whole contents of textfile into a string.
| Out[14]= |  |
|
This opens an input stream for the string.
| Out[15]= |  |
|
This gives the lines of text in the string that contain is.
| Out[16]= |  |
|
This resets the current position back to the beginning of the string.
| Out[17]= |  |
|
This finds the first occurrence of the in the string, and leaves the current point just after it.
| Out[18]= |  |
|
This reads the "word" which appears immediately after the.
| Out[19]= |  |
|
This closes the input stream.
| Out[20]= |  |
|