C#:循环多行字符串

发布于 2024-08-07 04:18:54 字数 52 浏览 4 评论 0原文

在不使用更多内存(例如不将其拆分为数组)的情况下循环遍历多行字符串的每一行的好方法是什么?

What is a good way to loop through each line of a multiline string without using much more memory (for example without splitting it into an array)?

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

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

发布评论

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

评论(8

无声无音无过去 2024-08-14 04:18:55

来自 MSDN 的 StringReader

    string textReaderText = "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("Original text:\n\n{0}", textReaderText);

    // From textReaderText, create a continuous paragraph 
    // with two spaces between each sentence.
    string aLine, aParagraph = null;
    StringReader strReader = new StringReader(textReaderText);
    while(true)
    {
        aLine = strReader.ReadLine();
        if(aLine != null)
        {
            aParagraph = aParagraph + aLine + " ";
        }
        else
        {
            aParagraph = aParagraph + "\n";
            break;
        }
    }
    Console.WriteLine("Modified text:\n\n{0}", aParagraph);

from MSDN for StringReader

    string textReaderText = "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("Original text:\n\n{0}", textReaderText);

    // From textReaderText, create a continuous paragraph 
    // with two spaces between each sentence.
    string aLine, aParagraph = null;
    StringReader strReader = new StringReader(textReaderText);
    while(true)
    {
        aLine = strReader.ReadLine();
        if(aLine != null)
        {
            aParagraph = aParagraph + aLine + " ";
        }
        else
        {
            aParagraph = aParagraph + "\n";
            break;
        }
    }
    Console.WriteLine("Modified text:\n\n{0}", aParagraph);
对你的占有欲 2024-08-14 04:18:55

尝试使用 String.Split 方法:

string text = @"First line
second line
third line";

foreach (string line in text.Split('\n'))
{
    // do something
}

Try using String.Split Method:

string text = @"First line
second line
third line";

foreach (string line in text.Split('\n'))
{
    // do something
}
青萝楚歌 2024-08-14 04:18:55

这是一个快速代码片段,它将查找字符串中的第一个非空行:

string line1;
while (
    ((line1 = sr.ReadLine()) != null) &&
    ((line1 = line1.Trim()).Length == 0)
)
{ /* Do nothing - just trying to find first non-empty line*/ }

if(line1 == null){ /* Error - no non-empty lines in string */ }

Here's a quick code snippet that will find the first non-empty line in a string:

string line1;
while (
    ((line1 = sr.ReadLine()) != null) &&
    ((line1 = line1.Trim()).Length == 0)
)
{ /* Do nothing - just trying to find first non-empty line*/ }

if(line1 == null){ /* Error - no non-empty lines in string */ }
望喜 2024-08-14 04:18:55

有时我认为我们可以使解决方案变得过于复杂,以避免重复一行代码。这就是我首先提出这个问题的原因。

经过一番思考后,我得出的结论是,最简单的解决方案是在循环之前和内部重复 ReadLine。

using (var stringReader = new StringReader(input))
{
    var line = await stringReader.ReadLineAsync();

    while (line != null)
    {
        // do something
        line = await stringReader.ReadLineAsync();
    }
}

我意识到这可能被认为不遵循 DRY 原则,但考虑到简单性,我认为值得考虑。

Sometimes I think we can overcomplicate the solution just to avoid repeating one line of code. This is the reason I landed on this question in the first place.

After thinking about it for a bit I came to the conclusion that the simplest solution is to repeat the ReadLine before and inside the loop.

using (var stringReader = new StringReader(input))
{
    var line = await stringReader.ReadLineAsync();

    while (line != null)
    {
        // do something
        line = await stringReader.ReadLineAsync();
    }
}

I realize this might be considered to not follow the DRY principle, but I think it's worth considering given the simplicity.

合久必婚 2024-08-14 04:18:55

您可以使用扩展方法:

public static IEnumerable<string> EnumerateLines(this string source)
{
  ArgumentNullException.ThrowIfNull(source);

  using StringReader reader = new StringReader(source);

  while(reader.ReadLine() is { } line)
  {
    yield return line;
  }
}

You could use an extension method:

public static IEnumerable<string> EnumerateLines(this string source)
{
  ArgumentNullException.ThrowIfNull(source);

  using StringReader reader = new StringReader(source);

  while(reader.ReadLine() is { } line)
  {
    yield return line;
  }
}
夏花。依旧 2024-08-14 04:18:54

我建议结合使用 StringReader 和我的 LineReader 类,该类是 MiscUtil,但也可以在这个 StackOverflow 答案中找到 - 您可以轻松地将该类复制到您自己的实用程序项目中。你可以像这样使用它:

string text = @"First line
second line
third line";

foreach (string line in new LineReader(() => new StringReader(text)))
{
    Console.WriteLine(line);
}

循环遍历字符串数据体(无论是文件还是其他什么)中的所有行是如此常见,以至于它不应该要求调用代码测试 null 等:)话虽如此,如果您确实想要进行手动循环,与 Fredrik 相比,我通常更喜欢这种形式:

using (StringReader reader = new StringReader(input))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // Do something with the line
    }
}

这样您只需测试一次无效性,并且不必考虑do/while 循环(由于某种原因,它总是比直接的 while 循环花费更多的精力来阅读)。

I suggest using a combination of StringReader and my LineReader class, which is part of MiscUtil but also available in this StackOverflow answer - you can easily copy just that class into your own utility project. You'd use it like this:

string text = @"First line
second line
third line";

foreach (string line in new LineReader(() => new StringReader(text)))
{
    Console.WriteLine(line);
}

Looping over all the lines in a body of string data (whether that's a file or whatever) is so common that it shouldn't require the calling code to be testing for null etc :) Having said that, if you do want to do a manual loop, this is the form that I typically prefer over Fredrik's:

using (StringReader reader = new StringReader(input))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // Do something with the line
    }
}

This way you only have to test for nullity once, and you don't have to think about a do/while loop either (which for some reason always takes me more effort to read than a straight while loop).

夏见 2024-08-14 04:18:54

您可以使用 StringReader 一次读取一行:

using (StringReader reader = new StringReader(input))
{
    string line = string.Empty;
    do
    {
        line = reader.ReadLine();
        if (line != null)
        {
            // do something with the line
        }

    } while (line != null);
}

You can use a StringReader to read a line at a time:

using (StringReader reader = new StringReader(input))
{
    string line = string.Empty;
    do
    {
        line = reader.ReadLine();
        if (line != null)
        {
            // do something with the line
        }

    } while (line != null);
}
情感失落者 2024-08-14 04:18:54

我知道这个问题已经得到解答,但我想添加我自己的答案:

using (var reader = new StringReader(multiLineString))
{
    for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
    {
        // Do something with the line
    }
}

I know this has been answered, but I'd like to add my own answer:

using (var reader = new StringReader(multiLineString))
{
    for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
    {
        // Do something with the line
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文