- Multiple ways to add newline into a String in C#
- Table of Contents
- Adding a New line using Environment.NewLine in a given string after a specific character
- Adding New Line using «\n» in C#
- Adding Line Break using Console.WriteLine()
- Multiple Lines using Single Console.WriteLine()
- Environment. New Line Свойство
- Значение свойства
- Примеры
- Комментарии
- 6 Ways to Insert a New Line in C# and ASP.NET
- Using Parameter-less Console.WriteLine() to Add a New Line
- Injecting New Lines within the Same String
- Using Environment.NewLine
- Using the ASCII Literal of a New Line
- Using \r\n to Insert a New Line
- Inserting New Lines in ASP.NET for an Existing String
- Read Next
Multiple ways to add newline into a String in C#
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); >>
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()"); >>
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.
Console.WriteLine(@"Hello World Welcome to qawithexperts Multiple lines using Single Console.WriteLine");
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().
Environment. New Line Свойство
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Возвращает строку, обозначающую в данной среде начало новой строки.
public: static property System::String ^ NewLine < System::String ^ get(); >;
public static string NewLine
member this.NewLine : string
Public Shared ReadOnly Property NewLine As String
Значение свойства
\r\n для платформ, отличных от Unix, или \n для платформ Unix.
Примеры
В следующем примере показаны две строки, разделенные новой строкой.
// Sample for the Environment::NewLine property using namespace System; int main() < Console::WriteLine(); Console::WriteLine("NewLine: first line second line", Environment::NewLine); > /* This example produces the following results: NewLine: first line second line */
// Sample for the Environment.NewLine property using System; class Sample < public static void Main() < Console.WriteLine(); Console.WriteLine($"NewLine: first line second line"); > > /* This example produces the following results: NewLine: first line second line */
// Sample for the Environment.NewLine property open System printfn $"\nNewLine: first line second line" // This example produces the following results: // NewLine: // first line // second line
' Sample for the Environment.NewLine property Class Sample Public Shared Sub Main() Console.WriteLine() Console.WriteLine($"NewLine: first line second line") End Sub End Class 'This example produces the following results: ' 'NewLine: ' first line ' second line '
Комментарии
Значение NewLine свойства является константой, настраиваемой специально для текущей платформы и реализации платформа .NET Framework. Дополнительные сведения о escape-символах в значении свойства см. в разделе «Escape-символы».
Функциональность, предоставляемая NewLine часто означает термины newline, строка, разрыв строки, возврат каретки, CRLF и конец строки.
NewLineможно использовать в сочетании с поддержкой новой строки для конкретного языка, например escape-символы «\r» и «\n» в Microsoft C# и C/C++, или vbCrLf в Microsoft Visual Basic.
NewLineавтоматически добавляется в текст, обрабатываемый методамиConsole.WriteLine.StringBuilder.AppendLine
6 Ways to Insert a New Line in C# and ASP.NET
The easiest guide providing 6 different ways to add a new line in C# and ASP.NET with code and screenshots.
Dot Net C# is one of the greatest managed programming languages. A managed programming language interprets or builds your code and transforms it into another executable format to be executed on your operating system.
For example, in .Net, when you write some code and try to build it, the Just-in-Time JIT compilation compiles your code and transforms it to machine instructions, which then will be executed by Common Language Runtime CLR.
For more information about CLR, see Common Language Runtime.
In this post, we will discuss 6 different ways to insert a new line in C# and test our code on a console application, and we will emphasize the relationship between one or more of these ways with what we discussed earlier about CLR.
The 6 ways to insert new lines in C# are as follows:
Using Parameter-less Console.WriteLine() to Add a New Line
The easiest way to inject a new line in a console application is to use a parameter-less Console.WriteLine() . For example:
Console.WriteLine(«This is a line»);
Console.WriteLine();
Console.WriteLine(«This is another line»);
As mentioned in Microsoft’s Documentation, running a Console.WriteLine() without any parameters translates to a line terminator, as shown in the next screenshot.
So as shown above, a parameter-less Console.WriteLine() defaults to one line break between two lines. You can also change this default preset by any spacing you require. For example, you can change the Console.WriteLine() to enter two lines instead of one. This can be handled by the following code example.
The above code, will let every Console.WriteLine() call insert 2 lines. So if you passed a string to any Console.WriteLine() , a new line will be added in addition to the current input string. Likewise, the parameter-less Console.WriteLine() will actually enter two lines instead of just one.
The output of the above code will look like this:
Notice that, there is one line entered after the first Console.WriteLine() , then two blank lines for the second Console.WriteLine() , then one blank line after the third call.
Injecting New Lines within the Same String
The second way to insert a new line in a string is to place \n within your string. For example:
The above code will run as shown in the next screenshot:
As clearly noticed, that \n could successfully insert a new line inside the same string.
Using Environment.NewLine
Another way to add a new line in a string is using Environment.NewLine . For example:
The above code will produce the same result as the previous screenshot.
Using the ASCII Literal of a New Line
This method is similar to the \n . But instead, you can use the ASCII literal that represents a new line. For example:
This new line ASCII literal \x0A will also insert a new line in the string above.
Using \r\n to Insert a New Line
You can also inject \r\n in a string to insert a new line. For example:
The above code will successfully insert a new line using \r\n . But what’s the difference between \r\n and \n ?
\n represents a new line, while \r represents a carriage return, which means the cursor will be moved to the very far left position. For more information, see Difference between \r and \r\n.
Inserting New Lines in ASP.NET for an Existing String
Line breaks in HTML or ASP.NET is represented by the < br/>tag. In some cases, you will need to convert an existing string that contains new lines to a valid HTML code that includes < br/>tags. To convert a string’s new lines to HTML line breaks you can use the following method that leverages regular expressions.
The above method is designed to be an extension method. Include the method in a separate file, then include it in your code through a using statement then call the method as follows:
You can test the above regular expression on this link.
If you have any questions or want to improve any of the above methods, feel free to drop me a comment.
Read Next
The following articles are related to 6 ways to insert a new line in c# and asp.net.
Select2 CDN JS Complete Ajax Example in 3 Simple Steps A step-by-step guide that provides 3 easy steps to easily set up and render a working jQuery Ajax Select2 dropdown list using CDN JS and CSS files
Create Modern ASP.NET MVC Dropdown Lists — 3 Steps The complete guide to creating modern UI drop down lists in ASP.NET MVC in very simple steps using Razor and Bootstrap for professional results