Archive

Posts Tagged ‘string’

How To: Read String Line by Line

January 19, 2011 Leave a comment

Breaking a string containing multi-line text to a list of lines can be easily done using StringReader. Here is a method that does this and small test program:


class Program
{
    static void Main(string[] args)
    {
        IList<string> lines = BreakLines("This is a test for breaking multiline string \nto a list of lines.");

        foreach (var item in lines)
        {
            Console.WriteLine(item);
        }

        Console.ReadLine();
    }

    private static IList<string> BreakLines(string text)
    {
        IList<string> lines = new List<string>();

        using (StringReader reader = new StringReader(text))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                lines.Add(line);
            }
        }

        return lines;
    }
}

 

Categories: Development, How To Tags: ,
Follow

Get every new post delivered to your Inbox.