StringReader和StringWriter是C#中用于從字符串中讀取數(shù)據(jù)和向字符串中寫入數(shù)據(jù)的類。以下是它們的基本用法示例:
使用StringReader從字符串中讀取數(shù)據(jù):
string input = "Hello World!";
using (StringReader reader = new StringReader(input))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
使用StringWriter向字符串中寫入數(shù)據(jù):
using (StringWriter writer = new StringWriter())
{
writer.WriteLine("Hello");
writer.WriteLine("World");
string result = writer.ToString();
Console.WriteLine(result);
}
在這兩個示例中,我們首先實例化了StringReader和StringWriter類,然后分別使用它們從字符串中讀取數(shù)據(jù)和向字符串中寫入數(shù)據(jù)。最后,我們將結(jié)果輸出到控制臺。