C# StringReader
In C#, the StringReader class is used to read text data from a string. It is useful for reading text data that has been previously loaded into a string object. In this tutorial, we'll discuss how to use the StringReader class in C#.
Syntax
The syntax for creating a StringReader object in C# is as follows:
StringReader sr = new StringReader(str);
Here, "str" is the string object containing the text data to be read.
Example
Let's say we have a string containing comma-separated values that we want to read into an array. We can use the StringReader class to achieve this as follows:
string data = "apple,banana,orange,grape";
StringReader sr = new StringReader(data);
string[] values = sr.ReadLine().Split(',');
foreach (string value in values) {
Console.WriteLine(value);
}
Output
When we run the example code above, the following output will be produced:
apple
banana
orange
grape
This is because the code reads the values in the comma-separated string into an array and prints each value to the console.
Explanation
In the example above, we created a string containing comma-separated values and used a StringReader object to read the values into an array. We split the data into an array using the Split() method, and then printed each value to the console using a foreach loop.
Use
The StringReader class is useful for reading text data that has been previously loaded into a string object. It allows you to read a string line by line or character by character.
Important Points
- The StringReader class is part of the System.IO namespace.
- The StringReader class provides a Read() method to read a single character, a ReadLine() method to read a line of text, and a Peek() method to peek at the next character without reading it.
- The StringReader class is a disposable object, so make sure to dispose of it properly when you are finished using it.
Summary
In this tutorial, we discussed how to use the StringReader class in C#. We covered the syntax, example, output, explanation, use, and important points of the StringReader class in C#. With this knowledge, you can now use the StringReader class to read text data from a string in your C# applications.