How to replace line breaks in a string in C#?


Let us take we have to eliminate the line breaks, space and tab space from the below string.

eliminate.jpg

Example

We can make use of Replace() extension method of string to do it.

 Live Demo

using System;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         string testString = "Hello 
\r beautiful
\t world";          string replacedValue = testString.Replace("
\r", "_").Replace("
\t", "_");          Console.WriteLine(replacedValue);          Console.ReadLine();       }    } }

Output

The output of the above code is

Hello _ beautiful _ world

Example

We can also make use of Regex to perform the same operation. Regex is available in System.Text.RegularExpressions namespace.

 Live Demo

using System;
using System.Text.RegularExpressions;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         string testString = "Hello 
\r beautiful
\t world";          string replacedValue = Regex.Replace(testString, @"
\r|
\t", "_");          Console.WriteLine(replacedValue);          Console.ReadLine();       }    } }

Output

The output of the above code is

Hello _ beautiful _ world

Updated on: 08-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements