C# Program For Counting Lines in a String
Last Updated :
23 Jul, 2025
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
Similar Reads
Introduction
C# TutorialC# (pronounced "C-sharp") is a modern, versatile, object-oriented programming language developed by Microsoft in 2000 that runs on the .NET Framework. Whether you're creating Windows applications, diving into Unity game development, or working on enterprise solutions, C# is one of the top choices fo
4 min read
Introduction to .NET FrameworkThe .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The .NET framework is primarily used on Windows, while .NET Core (which evolved into
6 min read
C# .NET Framework (Basic Architecture and Component Stack)C# (C-Sharp) is a modern, object-oriented programming language developed by Microsoft in 2000. It is a part of the .NET ecosystem and is widely used for building desktop, web, mobile, cloud, and enterprise applications. This is originally tied to the .NET Framework, C# has evolved to be the primary
6 min read
C# Hello WorldThe Hello World Program is the most basic program when we dive into a new programming language. This simply prints "Hello World!" on the console. In C#, a basic program consists of the following:A Namespace DeclarationClass Declaration & DefinitionClass Members(like variables, methods, etc.)Main
4 min read
Common Language Runtime (CLR) in C#The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the execution of .NET applications. It is responsible for loading and executing the code written in various .NET programming languages, including C#, VB.NET, F#, and others.When a C# program is compiled, th
4 min read
Fundamentals
C# IdentifiersIn programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the user-defined name of the program components. In C#, an identifier can be a class name, method name, variable name, or label. Example: public class GFG { static public void Main () { int
2 min read
C# Data TypesData types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C# each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given pr
7 min read
C# VariablesIn C#, variables are containers used to store data values during program execution. So basically, a Variable is a placeholder of the information which can be changed at runtime. And variables allows to Retrieve and Manipulate the stored information. In Brief Defination: When a user enters a new valu
4 min read
C# LiteralsIn C#, a literal is a fixed value used in a program. These values are directly written into the code and can be used by variables. A literal can be an integer, floating-point number, string, character, boolean, or even null. Example:// Here 100 is a constant/literal.int x = 100; Types of Literals in
5 min read
C# OperatorsIn C#, Operators are special types of symbols which perform operations on variables or values. It is a fundamental part of language which plays an important role in performing different mathematical operations. It takes one or more operands and performs operations to produce a result.Types of Operat
7 min read
C# KeywordsKeywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to be used as variable names or objects. Doing this will result in a compile-time error.Example:C#// C# Program to illustrate the
5 min read
Control Statements
C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of program based on certain conditions. These
5 min read
C# Switch StatementIn C#, Switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value of the expression. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type.
4 min read
C# LoopsLooping in a programming language is a way to execute a statement or a set of statements multiple times, depending on the result of the condition to be evaluated to execute statements. The result condition should be true to execute statements within loops.Types of Loops in C#Loops are mainly divided
4 min read
C# Jump Statements (Break, Continue, Goto, Return and Throw)In C#, Jump statements are used to transfer control from one point to another point in the program due to some specified code while executing the program. In, this article, we will learn to different jump statements available to work in C#.Types of Jump StatementsThere are mainly five keywords in th
4 min read
OOP Concepts
Methods
Arrays
C# ArraysAn array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array spe
8 min read
C# Jagged ArraysA jagged array is an array of arrays, where each element in the main array can have a different length. In simpler terms, a jagged array is an array whose elements are themselves arrays. These inner arrays can have different lengths. Can also be mixed with multidimensional arrays. The number of rows
4 min read
C# Array ClassArray class in C# is part of the System namespace and provides methods for creating, searching, and sorting arrays. The Array class is not part of the System.Collections namespace, but it is still considered as a collection because it is based on the IList interface. The Array class is the base clas
7 min read
How to Sort an Array in C# | Array.Sort() Method Set - 1Array.Sort Method in C# is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method as follows:Sort<T>(T[]) MethodSort<T>(T[], IComparer<T>) MethodSort<T>(T[], Int32, Int32) MethodSort<T>(T[], Comparison<T>) Method
8 min read
How to find the rank of an array in C#Array.Rank Property is used to get the rank of the Array. Rank is the number of dimensions of an array. For example, 1-D array returns 1, a 2-D array returns 2, and so on. Syntax: public int Rank { get; } Property Value: It returns the rank (number of dimensions) of the Array of type System.Int32. B
2 min read
ArrayList
String
Tuple
Indexers