C#中:通过多行字符串行循环 [英] C#: Looping through lines of multiline string

查看:631
本文介绍了C#中:通过多行字符串行循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是没有使用更多的内存(例如,不要把它变成一个数组),以通过多行字符串的每一行循环的好办法?

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)?

推荐答案

我建议使用 StringReader 我的 LineReader 类的组合,这是一部分 MiscUtil 但在的这个StackOverflow的答案 - 您可以轻松地只是类复制到自己的公用事业项目。你会使用这样的:

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
    }
}

这样,您只需要测试无效一次,你不必去想一个do / while循环要么(由于某种原因总是我付出更多的努力比直while循环读取)。

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).

这篇关于C#中:通过多行字符串行循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆