📜  C#StringReader(1)

📅  最后修改于: 2023-12-03 15:14:27.523000             🧑  作者: Mango

C# StringReader

Introduction

StringReader is a class in C# that reads a string as text line by line. It inherits from the TextReader class and provides a read-only stream of text characters from a specified string. The StringReader class is useful when you have a string with some formatted text, and you want to parse or read it line by line.

Syntax
public sealed class StringReader : TextReader
Constructors

The StringReader class has only one constructor that takes a string as a parameter.

public StringReader(string s)
Properties

The StringReader class has the following properties:

| Property | Description | | ----------------- | ------------------------------------------------------------ | | BaseStream | Gets the underlying stream from which the StringReader object reads. | | CurrentEncoding | Gets the Encoding used by the current instance of the StringReader class. |

Methods

The StringReader class provides the following methods:

| Method | Description | | ---------------- | ------------------------------------------------------------ | | Close | Closes the StringReader object. | | Dispose | Releases all resources used by the current instance of the StringReader class. | | Peek | Returns the next available character without reading it from the current source. | | Read | Reads the next character from the input string and advances the character position by one character. | | ReadBlock | Reads a specified maximum number of characters from the current string and writes the data to a buffer, beginning at the specified index. | | ReadLine | Reads a line of characters from the input string and returns the data as a string. | | ReadToEnd | Reads all characters from the current position to the end of the input string and returns them as one string. |

Example
using System;
using System.IO;

class Example
{
    static void Main()
    {
        string input = "Hello\nWorld\n!";
        using (StringReader reader = new StringReader(input))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}
Conclusion

In summary, the StringReader class in C# provides an easy way to read a string line by line. With the StringReader class, you can easily parse or read a formatted text string in your program.