This section talks about string I/O. This concept at first might sound strange—after all, we’ve been talking about file I/O until this point. But it is often very convenient to treat strings as files and write data to them just as you write data to a file.
This section covers three important classes: StringReader, StringBuilder, and StringWriter. The StringReader class implements a TextReader that reads from a string.
The StringBuilder class represents a custom constructor for strings and is used in conjunction with the String class to carry out modifications upon strings. It is convenient for situations in which it is desirable to modify a string, perhaps by removing, replacing, or inserting characters, without creating a new string subsequent to each modification. The methods contained within this class do not return a new StringBuilder object unless specified otherwise.
Equals has not been overridden in StringBuilder (as it is in String) because the contract with Equals() states that if a.Equals(b) is true it will always be true. Because the string of characters contained in a StringBuilder can change, it is not possible to implement Equals() based on the content of a StringBuilder.
The StringWriter class writes characters to a string.
The example I created to demonstrate these three classes isn’t necessarily practical, but it clearly shows how to use these classes. The example enables users to enter two sets of string information by providing two editable text boxes. These sets of text data are then read one character at a time to produce a resultant string. To show the difference between the two strings (in addition to the distinct possibility that the data will be different), the font color alternates.
Figure 5.10 shows the example in action. The two sets of text data have been read and combined into one string. Listing 5.11 shows the code that makes it work.
18.117.235.185