C# Program to Count the Number of Lines in a String

This is a C# Program to count lines in a string.

Problem Description

This C# Program Counts Lines in a String.

Problem Solution

Here the Number of Lines in the given string is calculated and are stored in count variable and are displayed.

Program/Source Code

Here is source code of the C# Program to Count Lines in a String. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

 * C# Program to Count Lines in a String
using System;
using System.Text.RegularExpressions;
class Program
    static void Main()
        long a = countstring("This is \n Sanfoundry\n Website");
        Console.WriteLine("Number of Lines in the String : {0}",a);
    static long countstring(string s)
        long count = 1;
        int start = 0;
        while ((start = s.IndexOf('\n', start)) != -1)
        return count;
Program Explanation

This C# program is used to count lines in a string. Using while loop count the lines in string. Check the index of sentence is equal to -1. If the condition is true, then execute the statement and print the number of lines in the string.

Runtime Test Cases
Number of Lines in the String : 3

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

If you wish to look at all C# Programming examples, go to 1000 C# Programs.

If you find any mistake above, kindly email to [email protected]

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.