while switch for crear c# loops multilinestring

for - switch c#



C#: Looping a través de líneas de cadena multilínea (5)

Aquí hay un fragmento de código rápido que encontrará la primera línea no vacía en una cadena:

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

¿Cuál es una buena forma de recorrer cada línea de una cadena multilínea sin utilizar mucha más memoria (por ejemplo, sin dividirla en una matriz)?


Puede usar un StringReader para leer una línea a la vez:

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


Sé que esto ha sido respondido, pero me gustaría agregar mi propia respuesta:

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


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


Sugiero usar una combinación de StringReader y mi clase LineReader , que es parte de MiscUtil pero también está disponible en esta respuesta de ; puede copiar fácilmente esa clase en su propio proyecto de utilidad. Lo usarías así:

string text = @"First line second line third line"; foreach (string line in new LineReader(() => new StringReader(text))) { Console.WriteLine(line); }

Looping sobre todas las líneas en un cuerpo de datos de cadena (ya sea un archivo o lo que sea) es tan común que no debería requerir que el código de llamada esté probando nulo, etc. :) Dicho esto, si desea hacer una bucle manual, esta es la forma que prefiero más que la de Fredrik:

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

De esta manera, solo tienes que probar la nulidad una vez, y no tienes que pensar en un ciclo do / while tampoco (que por alguna razón siempre me toma más esfuerzo leer que un ciclo straight while).