Remove new line from a string

Remove new line from a string c# vb.net asp.net

A String object is a sequential collection of System.Char objects that represent a string. The String object is Immutable , it cannot be modified once it created, that means every time you use any operation in the String object , you create a new String Object. A newline also known as a line ending, end of line or line break. In this lesson we will we examine how to remove new line characters from a string.

The easiest way is to use RegEx

using System.Text.RegularExpressions;

C#

string str = "First line \r\n Second Line \r\n Third Line \r\n Forth Line";
str = Regex.Replace(str, @"\t\n\r", "");
MessageBox.Show(str);

VB.Net

Dim str As String = "First line " & vbLf & " Second Line " & vbTab & " Third Line " & vbCr & " Forth Line"
str = Regex.Replace(str, "\t\n\r", "")
MessageBox.Show(str)

Output :

First line Second Line Third Line Forth Line

How can I remove "\r\n" from a string

C#

string str = "First line \r\n Second Line \r\n Third Line \r\n Forth Line";
str = str.Replace("\n", String.Empty);
str = str.Replace("\r", String.Empty);
str = str.Replace("\t", String.Empty);
MessageBox.Show(str);

VB.Net

Dim str As String = "First line " & vbLf & " Second Line " & vbTab & " Third Line " & vbCr & " Forth Line"
str = str.Replace(vbLf, [String].Empty)
str = str.Replace(vbCr, [String].Empty)
str = str.Replace(vbTab, [String].Empty)
MessageBox.Show(str)

Output :

First line Second Line Third Line Forth Line

Replace Line Breaks within a string

str.Replace(System.Environment.NewLine, "character you want to replace");

The following program replace the line breaks to coma(,) seperated words.

C#

string str = "First line \r\n Second Line \r\n Third Line \r\n Forth Line";
str = str.Replace(System.Environment.NewLine, ",");
MessageBox.Show(str);

VB.Net

Dim str As String = "First line " & vbCr & vbLf & " Second Line " & vbCr & vbLf & " Third Line " & vbCr & vbLf & " Forth Line"
str = Regex.Replace(str, "\t\n\r", "")
MessageBox.Show(str)

Output :

First line, Second Line, Third Line, Forth Line


NEXT.....Remove non alphanumeric