C# program to count the lines in a given string

Here, we are going to learn how to count the lines in a given string in C#?
Submitted by Nidhi, on October 13, 2020

Here, we will count the lines in a specified string.

Program:

The source code to count the lines in a given string is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to count the lines in a given string.

using System;

class Program
{
    static int CountLines(string str)
    {
        int lines = 1;
        int index = 0;
        while (true)
        {
            index = str.IndexOf('\n', index);
            if (index < 0)
                break;
            lines++;
            index++;
        }
        return lines;
    }
    static void Main()
    {
        string str="Mumbai Indians\nDelhi Capitals\nRajsthan Royals";

        int lines = 0;

        Console.WriteLine("Lines:");
        Console.WriteLine(str);
        lines=CountLines(str);
        Console.WriteLine("Total lines in a string: "+lines);
    }
    
}

Output:

Lines:
Mumbai Indians
Delhi Capitals
Rajsthan Royals
Total lines in a string: 3
Press any key to continue . . .

Explanation:

Here, we created a Program class that contains two static methods CountLines() and Main().

In the CountLines() method, we find the "\n" characters to count lines in a specified string using the IndexOf() method. This method returns the count of lines to the Main() method.

In the Main() method, we created the string str initialized with "Mumbai Indians\nDelhi Capitals\nRajsthan Royals" and then count lines and print the count on the console screen.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.