ZetCode

C# StringReader

最后修改于 2023 年 7 月 5 日

C# StringReader 教程展示了如何使用 StringReader 在 C# 中读取字符串。

C# 中的输入和输出基于流。Stream 是所有流的抽象基类。流是对字节序列的抽象,例如文件、输入/输出设备、进程间通信管道或 TCP/IP 套接字。

C# StringReader

StringReader 从字符串中读取文本数据。它可以同步或异步读取数据。读取操作基于流。

C# StringReader ReadToEnd

ReadToEnd 方法从当前位置读取所有字符到字符串的末尾,并将它们作为单个字符串返回。

Program.cs
using System.Text;

var sb = new StringBuilder();
sb.AppendLine("There is a hawk in the sky.");
sb.AppendLine("The sun is shining.");
sb.AppendLine("The flowers are blossoming.");

using var reader = new StringReader(sb.ToString());
string text = reader.ReadToEnd();
Console.WriteLine(text);

该示例使用 StringBuilder 构建一个字符串,然后使用 StringReaderReadToEnd 读取文本。

$ dotnet run
There is a hawk in the sky.
The sun is shining.
The flowers are blossoming.

C# StringReader ReadLine

ReadLine 方法从当前字符串读取一行字符,并将数据作为字符串返回。

Program.cs
var text = @"The Battle of Thermopylae was fought between an alliance 
of Greek city-states, led by King Leonidas of Sparta, and the Persian Empire of 
Xerxes I over the course of three days, during the second Persian invasion of Greece.";

using var sr = new StringReader(text);

int count = 0;
string line;

while ((line = sr.ReadLine()) != null)
{
    count++;
    Console.WriteLine("Line {0}: {1}", count, line);
}

在该示例中,我们计算多行字符串的行数。

while ((line = sr.ReadLine()) != null)
{

ReadLine 方法从当前字符串返回下一行,如果到达字符串的末尾,则返回 null

$ dotnet run
Line 1: The Battle of Thermopylae was fought between an alliance
Line 2: of Greek city-states, led by King Leonidas of Sparta, and the Persian Empire of
Line 3: Xerxes I over the course of three days, during the second Persian invasion of Greece.

C# StringReader Read

Read 方法从输入字符串中读取下一个字符,并将字符位置前进一个字符。

Program.cs
var text = "There is an old hawk in the sky.";

using var reader = new StringReader(text);

int count = 0;
char mychar = 'h';
int n;

while ((n = reader.Read()) != -1)
{
    char c = (char) n;

    if (c.Equals(mychar))
    {
        count++;
    }
}

Console.WriteLine($"There are {count} '{mychar}' characters in the string");

在该示例中,我们计算文本中字符“h”的出现次数。

while ((n = reader.Read()) != -1)
{

Read 方法从底层字符串返回下一个字符,如果没有更多字符可用,则返回 -1。

$ dotnet run
There are 3 'h' characters in the string

来源

StringReader 类 - 语言参考

在本文中,我们已经使用 StringReader 在 C# 中读取了字符串。

作者

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

列出所有 C# 教程