ZetCode

C# StringReader

最后修改于 2025 年 4 月 20 日

本教程解释了如何在 C# 中使用 StringReader 类来读取和处理字符串数据。StringReader 提供了按字符或逐行读取字符串的方法。

StringReader 类实现了一个从字符串读取的 TextReader。它提供了与 StreamReader 类似的方法,但直接使用字符串。

当您需要逐行或逐字符处理字符串数据时,StringReader 非常有用。它通常与 StringWriter 一起用于构建字符串。

StringReader 基本示例

此示例演示了 StringReader 的基本用法,即按字符读取字符串。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string text = "Hello StringReader";
        
        using (StringReader reader = new StringReader(text))
        {
            int character;
            while ((character = reader.Read()) != -1)
            {
                Console.Write((char)character);
            }
        }
    }
}

该示例从一个字符串创建一个 StringReader,并按字符读取它。当到达字符串末尾时,Read() 方法返回 -1。在此示例中,我们使用字符串 "Hello StringReader" 初始化一个 StringReader

while 循环继续读取字符,直到 Read() 返回 -1。每个字符在打印之前都转换为 char。这演示了 StringReader 的基本逐字符读取功能。

使用 StringReader 读取行

StringReader 可以逐行读取字符串,这对于处理多行文本非常有用。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string lines = "First line\nSecond line\nThird line";
        
        using (StringReader reader = new StringReader(lines))
        {
            string line;
            int count = 1;
            
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine($"Line {count}: {line}");
                count++;
            }
        }
    }
}

当没有更多行可用时,ReadLine() 方法返回 null。此示例显示了如何处理多行字符串。输入字符串包含三行,由换行符分隔。

StringReader 使用 ReadLine() 顺序读取每一行,这会自动处理换行符。行计数器演示了如何在处理过程中跟踪行号。

读取字符块

StringReader 可以将字符块读取到数组中,这对于处理大型字符串非常有效。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string text = "The quick brown fox jumps over the lazy dog";
        
        using (StringReader reader = new StringReader(text))
        {
            char[] buffer = new char[10];
            int charsRead;
            
            while ((charsRead = reader.Read(buffer, 0, buffer.Length)) > 0)
            {
                Console.WriteLine($"Read {charsRead} chars: " + 
                    new string(buffer, 0, charsRead));
            }
        }
    }
}

Read(char[], int, int) 方法将字符读取到缓冲区数组中。它返回实际读取的字符数。此示例演示了以 10 个字符的块读取字符串。

缓冲区数组临时存储从 StringReader 读取的字符。charsRead 变量跟踪每次操作中实际读取的字符数。这种方法对于大型字符串来说是内存高效的。

预览字符

StringReader 允许使用 Peek() 方法预览下一个字符而不消耗它。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string text = "ABC123";
        
        using (StringReader reader = new StringReader(text))
        {
            int peek = reader.Peek();
            Console.WriteLine($"Peeked: {(char)peek}");
            
            int read = reader.Read();
            Console.WriteLine($"Read: {(char)read}");
        }
    }
}

就像 Read() 一样,Peek() 在字符串末尾返回 -1。此示例显示了预览和读取之间的区别。Peek() 方法允许查看下一个字符而不推进读取器的位置。

第一个字符 'A' 被预览,但仍然可以读取。随后的 Read() 然后消耗相同的字符。这对于解析字符串时的前瞻操作非常有用。

组合 StringReader 和 StringWriter

StringReader 通常与 StringWriter 一起用于字符串处理管道。

Program.cs
using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        string input = "line1\nline2\nline3";
        
        using (StringReader reader = new StringReader(input))
        using (StringWriter writer = new StringWriter())
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                writer.WriteLine(line.ToUpper());
            }
            
            Console.WriteLine("Processed output:");
            Console.WriteLine(writer.ToString());
        }
    }
}

此示例从 StringReader 读取行,处理它们(转换为大写),然后写入 StringWriter。StringReader 逐行读取输入字符串。每一行都转换为大写并写入 StringWriter

StringWriter 将处理后的行累积在其内部 StringBuilder 中。最后,使用 ToString() 检索完整的处理后的字符串。这演示了一种常见的文本处理管道模式。

读取到字符串末尾

ReadToEnd() 方法读取从当前位置到字符串末尾的所有剩余字符。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string text = "First part\nSecond part\nThird part";
        
        using (StringReader reader = new StringReader(text))
        {
            // Read and discard first line
            reader.ReadLine();
            
            // Read remaining content
            string remaining = reader.ReadToEnd();
            Console.WriteLine("Remaining content:");
            Console.WriteLine(remaining);
        }
    }
}

此示例读取并丢弃第一行,然后读取整个剩余内容。ReadLine() 调用跳过第一行。然后 ReadToEnd() 读取从当前位置到末尾的所有剩余文本。

当您需要在处理主要内容之前跳过文本数据中的标题或前言时,此方法很有用。该方法对于读取大量剩余文本非常有效。

处理空字符串

此示例演示了 StringReader 如何处理空字符串和不同的读取方法。

Program.cs
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string empty = "";
        string whitespace = "   ";
        
        Console.WriteLine("Testing empty string:");
        TestReader(empty);
        
        Console.WriteLine("\nTesting whitespace string:");
        TestReader(whitespace);
    }
    
    static void TestReader(string input)
    {
        using (StringReader reader = new StringReader(input))
        {
            Console.WriteLine($"Read(): {reader.Read()}");
            Console.WriteLine($"Peek(): {reader.Peek()}");
            Console.WriteLine($"ReadLine(): {reader.ReadLine() ?? "null"}");
            Console.WriteLine($"ReadToEnd(): \"{reader.ReadToEnd()}\"");
        }
    }
}

该示例显示了 StringReader 方法在空字符串和空白字符串中的返回值。对于空字符串,Read()Peek() 立即返回 -1。ReadLine() 返回 null,ReadToEnd() 返回一个空字符串。

对于空白,Read() 返回第一个空格字符,Peek() 在不推进的情况下执行相同的操作,ReadLine() 返回空白字符串,ReadToEnd() 返回整个空白字符串。这演示了边缘情况的行为。

来源

StringReader 类文档

本教程介绍了使用 StringReader 在 C# 中读取字符串数据,包括逐字符读取、行读取和块读取技术。

作者

我的名字是 Jan Bodnar,我是一位充满热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直在撰写编程文章。到目前为止,我已经撰写了超过 1,400 篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

列出所有 C# 教程