In our C# tutorial, you can read about C# strings , C# String Interpolation or Console.WriteLine() in C# print string with newline, but in this article I have provided multiple ways to insert a newline break into a string using C# Console application examples.
Table of Contents
Adding a New line using Environment.NewLine in a given string after a specific character
Suppose, you already have a string and you want to add a NewLine after a specific character, let's say "#", you want to replace all occurences of "#" in a given string with a newline, then you can simply use Environment.NewLine
var CurrentStr="Hello World#Welcome to qawithexperts#Thanks for reading";
Then you can use the below C# Console Application C#
using System;
public class Program
{
public static void Main()
{
var CurrentStr="Hello World#Welcome to qawithexperts#Thanks for reading";
//.Replace("oldCharacter","NewCharacter")
//here oldCharacter =#
//NewCharacter = New Line
CurrentStr = CurrentStr.Replace("#", System.Environment.NewLine);
Console.Write(CurrentStr);
}
}
Output:
Hello World
Welcome to qawithexperts
Thanks for reading
Adding New Line using "\n" in C#
For above example, you can also use "\n
" instead of System.Environment.NewLine
, so considering above example, we can have below C# code
var CurrentStr="Hello World#Welcome to qawithexperts#Thanks for reading";
CurrentStr = CurrentStr.Replace("#", "\n");
Console.Write(CurrentStr);
Adding Line Break using Console.WriteLine()
You can also simply use Console.WriteLine()
to add line break in your current solution.
Suppose, you want to simply add a blank line and want to move cursor in your console application to next line, you can simply use Console.WriteLine(), as shown in the below example
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World"); // This will print text and also move cursor to next line
Console.WriteLine("Welcome to qawithexperts");
Console.WriteLine("Thanks for reading example using Console.WriteLine()");
}
}
Output:
Hello World
Welcome to qawithexperts
Thanks for reading example using Console.WriteLine()
Multiple Lines using Single Console.WriteLine()
Suppose, you want to show multiple text line using 1 Console.WriteLine()
, then you can simply add "@" the beginning of the Console.WriteLine() string and split text in lines.
For example:
Console.WriteLine(@"Hello World
Welcome to qawithexperts
Multiple lines using Single Console.WriteLine");
Output:
Hello World
Welcome to qawithexperts
Multiple lines using Single Console.WriteLine
That's it, these are some of the ways to add new line in C#, but easiest one if to use "\n" or using Console.WriteLine().
You may also like to read: