CopyPastehas never been so tasty!

Count Number of Lines in string in C#

by anonymous

  • 0
  • 0
  • 0
75 views

Orignal Source:http://codingvilla.com/count-number-lines-string-csharp-single-article-616.aspx

 

Count Number of Lines in String:

 

String has many lines and sometimes we need to count those lines. To understand let us consider this example first we load a file which has string and we can count the number of lines in string. It can be done by the ‘ReadLine’ parameter less method which is from ‘StreamReader’ class and its namespace is System.IO.

 

First we write a method ‘CountLinesInFile’ and pass it a string as parameter and then count the number of lines in string.

 

To demonstrate make a console application and write the following code

 

 

Code:

 

 

classCount_Number_of_Lines_in_string

    {

staticvoid Main(string[] args)

        {

 

Console.WriteLine(CountLinesInFile("test.txt"));

Console.ReadLine();

        }

staticlongCountLinesInFile(string f)

    {

            long count = 0;

            using (StreamReader r = newStreamReader(f))

            {

            string line;

            while ((line = r.ReadLine()) != null)

                {

                        count++;

                }

            }

            return count;

    }

 

    }

Add A Comment: