Question

Qu'est-ce qu'un bon moyen de boucle à travers chaque ligne d'une chaîne multiligne sans utiliser beaucoup plus de mémoire (par exemple, sans le diviser en un tableau)?

Était-ce utile?

La solution

Je suggère d'utiliser une combinaison de StringReader et ma classe LineReader, qui fait partie de MiscUtil mais aussi disponible dans cette Stackoverflow répondre - vous pouvez facilement copier juste que classe dans votre propre projet d'utilité. Vous souhaitez l'utiliser comme ceci:

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

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

Looping sur toutes les lignes dans un ensemble de données de chaîne (que ce soit un fichier ou autre) est si commun qu'il ne devrait pas exiger le code d'appel pour être tester pour null etc :) Cela dit, si vous faire veulent faire une boucle manuelle, c'est la forme que je préfère en général sur Fredrik de:

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

De cette façon, il vous suffit de tester la nullité une fois, et vous ne devez pas penser à une boucle do / while soit (qui, pour une raison quelconque, me prend toujours plus d'efforts pour lire qu'une boucle while droite).

Autres conseils

Vous pouvez utiliser un StringReader pour lire ligne à la fois:

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

de MSDN pour 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);

Je sais que cela a été répondu, mais je voudrais ajouter ma propre réponse:

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

Voici un extrait de code rapide qui va trouver la première ligne non vide dans une chaîne:

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

Pour mettre à jour cette question ancienne pour 4 .NET, il y a maintenant une manière beaucoup plus propre:

var lines = File.ReadAllLines(filename);

foreach (string line in lines)
{
    Console.WriteLine(line);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top