Quel est un bon moyen de faire une boucle sur chaque ligne d'une chaîne multiligne sans utiliser beaucoup plus de mémoire (par exemple sans la diviser en un tableau)?C#: Bouclage à travers les lignes d'une chaîne multiligne
Répondre
Je suggère d'utiliser une combinaison de StringReader
et ma LineReader
classe, qui fait partie de MiscUtil mais également disponible en this StackOverflow answer - vous pouvez facilement copier juste cette classe dans votre propre projet utilitaire. 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 ne 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 suffit de tester la nullité une fois, et vous n'avez pas à penser à une boucle do/while non plus (qui, pour une raison quelconque, me prend toujours plus d'effort pour lire qu'une boucle while while).
Vous pouvez utiliser un StringReader
pour lire une 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);
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 */ }
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
}
}