Open In App

C# Program For Counting Lines in a String

Improve
Improve
Like Article
Like
Save
Share
Report

In C#, a string is a sequence of Unicode characters or an array of characters. The range of Unicode characters will be U+0000 to U+FFFF. A string is the representation of the text. In this article, we will create a C# program that will count the lines present in the given string. 

Example: 

Input  : hey geeks\n welcome to \n geeksforgeeks \n happy learning
Output : 4

Input  : welcome\n to geeksforgeeks
Output : 2

So we can do this task using the following methods:

  • By counting newline character
  • By using the Split() method
  • By using Regex.Matches Method
  • By using IndexOf() Method

Method 1: Counting newline character

Given a string with multiple lines we need to find a number of lines present in the string. As we know that the lines in a string are separated by a newline character (i.e. \n). So we use the following approach to count the number of lines present in the string.

Approach:

  • Initialize the variable count to zero.
  • Using a for loop iterate the given string.
  • if a new line character (\n) is encountered then increment the value of count by 1.
  • By the end of the iteration, the count variable will be the value of the number of lines present in the given string.

Example:

In this example, the entire string assigned in the “inputstr” variable will be iterated from left to right if a newline character is encountered then it represents that a new line is started so we increment the count of the number of lines by 1. At the end will get the number of lines In the string.

C#




// C# program to display the total number of lines
// present in the given string
using System;
 
class GFG{
     
static void Main()
{
     
    // Initializing a string with multiple lines.
    string intputstr = "hey geeks\n welcome to \n " +
                       "geeksforgeeks \n happy learning ";
    int count = 1;
     
    Console.WriteLine("Input String:\n" + intputstr);
     
    // Iterating the string from left to right
    for(int i = 0; i < intputstr.Length; i++)
    {
         
        // Checking if the character encountered is
        // a newline character if yes then increment
        // the value of count variable
        if (intputstr[i] == '\n')
            count++;
    }
     
    // Print the count
    Console.Write("\nNumber of new lines:" + count);
}
}


Output:

Input String:
hey geeks
welcome to
geeksforgeeks
happy learning

Number of new lines:4

Method 2: Using Split() method

The Split() method returns an array of strings generated by splitting the string separated by the delimiters passed as a parameter in the Split() method. Here we pass the \n as a parameter to the Split() method this split the line into strings and make an array of lines. Now find the length of the array that gives the number of lines present in the string.

Syntax:

str.Split(‘\n’).Length

Example:

In this example, the given string assigned in the “inputstr” variable is split into an array of strings, the splitting is done at every position where there is a newline character. Now the length of the array is the number of newlines present in the string.

C#




// C# program to display the total number of lines
// present in the given string. Using Split() method
using System;
 
class GFG{
     
static void Main()
{
    // Initializing a string with multiple lines.
    string intputstr = "hey geeks\n welcome to \n " +
                       "geeksforgeeks \n happy learning ";
     
    Console.WriteLine("Input String:\n" + intputstr);
                        
    // Now the Split('\n') method splits the newline
    // characters and returns an array of strings and
    // the Length is used to find the length of the array.
    int result = intputstr.Split('\n').Length;
     
    // Print the count
    Console.Write("\nNumber of new lines:" + result);
}
}


Output:

Input String:
hey geeks
welcome to
geeksforgeeks
happy learning

Number of new lines:4

Method 3: Using Regex.Matches() Method

We can also count the number of lines present in the given string using the Regex.Matches() method. This is used to search the specified input string for all occurrences of a given regular expression.

Syntax:

Regex.Matches(string inputstr, string matchpattern)

Here, this method takes two parameters named “inputstr” which represents the input string to search for a match, and “matchpattern” which represents the regular expression pattern to match with the inputstr.

Example: 

In this example, we will pass a regular expression \n” in the Matches() methods and find the number of occurrences of it and by adding a one to it we will get the number of lines in string.

C#




// C# program to count the lines in the given string
// Using Regular Expressions
using System;
using System.Text.RegularExpressions;
class GFG{
     
static void Main()
{
     
    // Input string
    string inputstr = "hey geeks\n welcome to \n " +
                       "geeksforgeeks \n happy learning ";
     
    Console.WriteLine("Input string:" + inputstr);
     
    // Passing string and regular expression to the
    // matches method we are adding 1 to number of
    // occurrences of \n because we will not have
    // \n at the end of last line
    int result = Regex.Matches(inputstr, "\n").Count + 1;
    Console.Write("Total number of lines: " + result);
}
}


Output:

Input string:hey geeks
welcome to
geeksforgeeks
happy learning
Total number of lines: 4

Method 4: Using IndexOf() Method

We can also count the number of lines present in the given string using the IndexOf() method. This method is used to find the zero-based index of the first occurrence of the given character in the given string. In this method, the searching of the specified character is starting from the specified position and if the character is not found then it will return -1.

Syntax: 

public int IndexOf(char y, int startchar)

This method takes two parameters the first parameter is char y, it represents the character to be searched and the second parameter is startchar represents the starting position in the form of an integer value from where the searching is to be started.

Example:

In this example, the while loop counts the total number of newlines present in the “inputstr”. In this while loop, we use IndexOf() method in which we pass “inputstr” and “\n”, then we check the index of the sequence is equal to true, if the value of the specified condition is true then execute the specified statements and display the output.

C++




// C# program to count the lines in the given string
// Using Regular Expressions
using System;
using System.Text.RegularExpressions;
class GFG{
     
static void Main()
{
     
    // Input string
    string inputstr = "hey geeks\n welcome to \n " +
                       "geeksforgeeks \n happy learning ";
     
    // Display the input string
    Console.WriteLine("Input string:" + inputstr);
     
    int countlines = 1;
    int startingpoint = 0;
     
    // Here the while loop counts the number
    // of lines present in the given string
    // Using IndexOf() method.
    while ((startingpoint = inputstr.IndexOf(
            '\n', startingpoint)) != -1)
    {
        countlines++;
        startingpoint++;
    }
     
    Console.Write("Total number of lines: " + countlines);
}
}


Output:

Input string:hey geeks
welcome to
geeksforgeeks
happy learning
Total number of lines: 4


Last Updated : 15 Nov, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads