首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# StringReader 與 StringWriter 實作雙倍行距與段落還原

     編輯:關於C語言

情境說明

展示如何使用 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());
        }
    }
}

關鍵類別說明

類別命名空間用途
StringReaderSystem.IO從字串建立 TextReader,支援 Read()、ReadLine()、ReadToEnd()。
StringWriterSystem.IO向字串緩衝區寫入文字,支援 Write()、WriteLine(),最終透過 ToString() 取得結果。

應用場景

  • 記憶體中文字處理管線(避免臨時檔案 I/O)。
  • 單元測試模擬 TextReader/TextWriter 介面。
  • 動態產生 XML/JSON/CSV 等文字格式。
  • 舊系統字串格式轉換(如本例的行距調整)。

進階提示

若需高效能大量字串操作,建議改用 StringBuilder 直接操作字元陣列,或使用 MemoryStream 搭配 StreamReader/Writer 處理二進位編碼轉換。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved