什么是通过一个多行字符串的每一行循环的好办法,而不使用更多的存储器(例如而不分裂成一个数组)?

有帮助吗?

解决方案

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

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

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

循环遍历字符串数据的身体所有行(不管是文件或其他)是很常见的,它不应该要求调用代码是这样说的测试等空:),如果你的的想做一个手动循环,这是我通常更喜欢弗雷德里克的形式:

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

此方式,您只需要测试无效一次,你不必去想一个do / while循环是(出于某种原因,总让我更努力,比直的,而循环读取)。

其他提示

可以使用 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);
}

这对于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);

我知道这已经回答了,但我想补充我自己的答案:

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

下面是一个简单的代码片段,会发现在字符串中的第一个非空行:

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

要更新.NET 4这个古老的问题,现在有一个更整洁的方式:

var lines = File.ReadAllLines(filename);

foreach (string line in lines)
{
    Console.WriteLine(line);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top