展示如何使用 StringReader 逐行讀取雙倍行距文字、合併為單一段落,再透過 StringWriter 依句點符號還原換行格式。
using System;
using System.IO;
public class StringRWDemo
{
public static void Main()
{
string original = "TextReader is the abstract base class of StreamReader and StringReader, which read characters from streams and strings, respectively.\n\n" +
"Create an instance of TextReader to open a text file for reading a specified range of characters, or to create a reader based on an existing stream.\n\n" +
"You can also use an instance of TextReader to read text from a custom backing store using the same APIs you would use for a string or a stream.\n\n";
Console.WriteLine("=== 原始文字(雙倍行距)===");
Console.WriteLine(original);
// 1. StringReader 逐行讀取,合併為單一段落
string paragraph = null;
using (StringReader reader = new StringReader(original))
{
string line;
while ((line = reader.ReadLine()) != null)
{
paragraph += line + " ";
}
}
Console.WriteLine("\n=== 合併後段落 ===");
Console.WriteLine(paragraph);
// 2. StringWriter 依句號還原換行
using (StringReader sr = new StringReader(paragraph))
using (StringWriter sw = new StringWriter())
{
int ch;
while ((ch = sr.Read()) != -1)
{
char c = (char)ch;
if (c == '.')
{
sw.Write(".\n\n");
sr.Read(); // 跳過句號後的空白
sr.Read();
}
else
{
sw.Write(c);
}
}
Console.WriteLine("\n=== 還原後文字 ===");
Console.WriteLine(sw.ToString());
}
}
}
| 類別 | 命名空間 | 用途 |
|---|---|---|
StringReader | System.IO | 從字串建立 TextReader,支援 Read()、ReadLine()、ReadToEnd()。 |
StringWriter | System.IO | 向字串緩衝區寫入文字,支援 Write()、WriteLine(),最終透過 ToString() 取得結果。 |
TextReader/TextWriter 介面。若需高效能大量字串操作,建議改用 StringBuilder 直接操作字元陣列,或使用 MemoryStream 搭配 StreamReader/Writer 處理二進位編碼轉換。