StringBuilder 与 StringWriter/StringReader

发布于 2024-09-12 09:11:49 字数 553 浏览 7 评论 0原文

我最近读到,StringWriterStringReader 用于从 StringBuilder 写入和读取。

好吧,当我使用 StringBuilder 对象时,它看起来是一个自给自足的类。

我们有各种读取和写入 StringBuilder 的方法,使用 StringBuilder.Append()Insert()Replace()Remove() 等...

  1. 什么是否可以使用 StringWriterStringReader,而 StringBuilder 本身无法完成?
  2. 它们的实际用途是什么?
  3. 他们没有采用 Stream 作为输入(因为任何其他编写器和读取器都将流作为要操作的构造函数参数),而是将 StringBuilder 作为输入,可能的原因是什么? >?

I recently read that in StringWriter and StringReader are used for writing and reading from StringBuilder.

Well when I use StringBuilder Object, it looks to be a self sufficient class.

We have every way of reading and writing the StringBuilder, using
StringBuilder.Append(), Insert(), Replace(), Remove() etc...

  1. What is the possible use of StringWriter and StringReader, which cannot be done by StringBuilder itself?
  2. What is the practical use of them?
  3. What could be the possible reason they are not taking up Stream as the input (Because any other writer and reader are taking the stream as the Constructor parameter to operate on) but the StringBuilder?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

萌辣 2024-09-19 09:11:49

StringWriter和StringReader的可能用途是什么,这是StringBuilder本身无法完成的?

StringReaderStringWriter 分别派生自 TextReaderTextWriter。因此,它们可以充当 TextReaderTextWriter 实例,而 stringStringBuilder 则不能,因为它们不这样做派生出这些类型中的任何一种。

它们的实际用途是什么?

当您拥有/想要的是 stringStringBuilder< 时,它们允许您调用需要 TextReaderTextWriter 的 API /代码>。

除了 StringBuilder 之外,他们不采用 Stream 作为输入(因为任何其他写入器和读取器都将流作为要操作的构造函数参数)的可能原因是什么?

因为它们不在流上工作;它们适用于 stringStringBuilder。它们只是简单的包装类,使这些类型适应需要不同接口的 API。请参阅:适配器模式

What is the possible use of StringWriter and StringReader, which cannot be done by StringBuilder itself?

StringReader and StringWriter derive from TextReader and TextWriter respectively. So what they can do act as a TextReader or TextWriter instance, which string or StringBuilder cannot because they do not derive either of those types.

What is the practical use of them?

They allow you to call APIs that are expecting a TextReader or TextWriter, when what you have/want is a string or StringBuilder.

What could be the possible reason they are not taking up Stream as the input (Because any other writer and reader are taking the stream as the Constructor parameter to operate on) but the StringBuilder?

Because they don't work on streams; they work on strings or StringBuilders. They're just simple wrapper classes that adapt these types for APIs expecting a different interface. See: adapter pattern.

栀子花开つ 2024-09-19 09:11:49

其他人已经说过了,但这是因为它们派生自 TextReader/TextWriter 并且可以用来代替它们。一方面,如果您只想将内容作为字符串,那么使用与文件相同的方法输出行更有意义。如果您希望输出在内存中跨越多行,为什么还要记住使用 StringBuilder 在每行末尾添加“\r\n”呢?如果您希望代码在仅使用“\n”作为换行符的系统上运行或格式化数据,该怎么办?

StringBuilder sb = new StringBuilder();
// will be invalid on systems that only use \n
sb.AppendFormat("{0:yyyy-MM-dd HH:mm:ss} - Start\r\n", DateTime.Now);
// still have to add an extra parameter
sb.AppendFormat("The current time is {0:yyyy-MM-dd HH:mm:ss}{1}", DateTime.Now,
    Environment.NewLine);

StringWriter sw = new StringWriter();
// Don't have to worry about it, method name tells you there's a line break
sw.WriteLine("{0:yyyy-MM-dd HH:mm:ss} - Start", DateTime.Now);
// no extra parameters
sw.WriteLine("The current time is {0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);

假设您想逐行处理文件,您可能会使用 StreamReader,而不是将整个文件加载到 StringBuilder 中并按换行符将其拆分到数组中,对吧?使用 StringReader,您可以使用完全相同的方法(只要它采用通用 TextReader),通过从 TextBox 或 Web 表单中的字符串创建 StringReader。

Linq2Sql DataContexts 有一个 Log 属性,您可以将其设置为 TextWriter,以便在执行查询之前输出查询,以准确查看正在运行的内容。您可以将其设置为附加到文件的 TextWriter,但您可以将 StringWriter 附加到它并在测试时在网页底部输出内容...

Others have said already, but it is because they derive from TextReader/TextWriter and can be used in place of them. For one thing it just makes more sense to use the same method for outputting lines that you use for a file if you only want the content as a string. If you want output that will span multiple lines in memory, why bother remembering to put "\r\n" at the end of every line with a StringBuilder? What if you want the code to run on or format data for a system that only uses "\n" for line breaks?

StringBuilder sb = new StringBuilder();
// will be invalid on systems that only use \n
sb.AppendFormat("{0:yyyy-MM-dd HH:mm:ss} - Start\r\n", DateTime.Now);
// still have to add an extra parameter
sb.AppendFormat("The current time is {0:yyyy-MM-dd HH:mm:ss}{1}", DateTime.Now,
    Environment.NewLine);

StringWriter sw = new StringWriter();
// Don't have to worry about it, method name tells you there's a line break
sw.WriteLine("{0:yyyy-MM-dd HH:mm:ss} - Start", DateTime.Now);
// no extra parameters
sw.WriteLine("The current time is {0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);

Say you want to process a file line by line, you would probably use a StreamReader instead of loading the whole file into a StringBuilder and splitting it by newline characters into an array, right? With StringReader you can use the exact same method (as long as it takes a generic TextReader) by creating the StringReader from a string from a TextBox or web form.

Linq2Sql DataContexts have a Log property you can set to a TextWriter to have your queries output before they are executed to see exactly what is being run. You can set this to a TextWriter attached to a file, but you could attach a StringWriter to it and output the contents at the bottom of your web page when testing...

久隐师 2024-09-19 09:11:49

您可以使用 StringReader 从字符串中读取所有整数。

private static void Main()
{
    var str = @"
                13
                13
                0 6
                0 5
                0 1
                0 2
                5 3
                6 4
                5 4
                3 4
                7 8
                9 10
                11 12
                9 11
                9 12";


    using (StandardInput input = new StandardInput(new StringReader(str)))
    {
        List<int> integers = new List<int>();
        int n;
        while ((n = input.ReadInt32()) != -1)
        {
            integers.Add(n);
        }
    }
}

标准输入类:

class StandardInput : IDisposable
{
    private readonly TextReader reader;

    public StandardInput(TextReader reader)
    {
        this.reader = reader;
    }

    public int ReadInt32()
    {
        while (!char.IsDigit((char)reader.Peek()) && reader.Peek() != -1)
        {
            reader.Read();
        }
        var builder = new StringBuilder();
        while (char.IsDigit((char) reader.Peek()))
            builder.Append((char) reader.Read());

        return builder.Length == 0 ? -1 : int.Parse(builder.ToString());
    }

    public double ReadDouble()
    {
        while (!char.IsDigit((char)reader.Peek()) && reader.Peek() != '.'
                                                  && reader.Peek() != -1)
        {
            reader.Read();
        }
        var builder = new StringBuilder();
        if (reader.Peek() == '.')
            builder.Append((char) reader.Read());
        while (char.IsDigit((char)reader.Peek()))
            builder.Append((char)reader.Read());
        if (reader.Peek() == '.' && !builder.ToString().Contains("."))
        {
            builder.Append((char)reader.Read());
            while (char.IsDigit((char)reader.Peek()))
                builder.Append((char)reader.Read());
        }
        return builder.Length == 0 ? -1 : double.Parse(builder.ToString());
    }

    public void Dispose()
    {
        reader.Dispose();
    }
}

You can use StringReader to read all integers from a string.

private static void Main()
{
    var str = @"
                13
                13
                0 6
                0 5
                0 1
                0 2
                5 3
                6 4
                5 4
                3 4
                7 8
                9 10
                11 12
                9 11
                9 12";


    using (StandardInput input = new StandardInput(new StringReader(str)))
    {
        List<int> integers = new List<int>();
        int n;
        while ((n = input.ReadInt32()) != -1)
        {
            integers.Add(n);
        }
    }
}

StandardInput Class:

class StandardInput : IDisposable
{
    private readonly TextReader reader;

    public StandardInput(TextReader reader)
    {
        this.reader = reader;
    }

    public int ReadInt32()
    {
        while (!char.IsDigit((char)reader.Peek()) && reader.Peek() != -1)
        {
            reader.Read();
        }
        var builder = new StringBuilder();
        while (char.IsDigit((char) reader.Peek()))
            builder.Append((char) reader.Read());

        return builder.Length == 0 ? -1 : int.Parse(builder.ToString());
    }

    public double ReadDouble()
    {
        while (!char.IsDigit((char)reader.Peek()) && reader.Peek() != '.'
                                                  && reader.Peek() != -1)
        {
            reader.Read();
        }
        var builder = new StringBuilder();
        if (reader.Peek() == '.')
            builder.Append((char) reader.Read());
        while (char.IsDigit((char)reader.Peek()))
            builder.Append((char)reader.Read());
        if (reader.Peek() == '.' && !builder.ToString().Contains("."))
        {
            builder.Append((char)reader.Read());
            while (char.IsDigit((char)reader.Peek()))
                builder.Append((char)reader.Read());
        }
        return builder.Length == 0 ? -1 : double.Parse(builder.ToString());
    }

    public void Dispose()
    {
        reader.Dispose();
    }
}
夜访吸血鬼 2024-09-19 09:11:49

我不确定是谁告诉您他们的目的是与 StringBuilder 一起使用,但这绝对是错误的。正如您所指出的,可以在不使用其他类的情况下读取和写入 StringBuilder。 StringWriter 和 StringReader 类扩展了 TextReader 和 TextWriter .Net Framework 基类,并提供类似流的功能来处理文本数据。例如,如果您需要使用某些 XmlDocument 类型的类,则某些方法允许您通过 TextReader 加载 Xml 数据,因此,如果您将 Xml 文本作为字符串变量,则可以将其加载到 StringReader 中然后将其提供给 XmlDocument。

I'm not sure who told you that their purpose was for use with StringBuilder, but that is absolutely incorrect. As you noted StringBuilder can be read from and written to without the use of another class. The StringWriter and StringReader classes extend the TextReader and TextWriter .Net Framework base classes and provide stream-like features for working with textual data. For example, if you need to work with some of the XmlDocument-type classes some of the methods allow you to load the Xml data via a TextReader, so if you have the Xml text as a string variable, you could load it into a StringReader and then supply it to the XmlDocument.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文