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

CsharpServer Side ProgrammingProgramming

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 \n\r beautiful \n\t world";
         string replacedValue = testString.Replace("\n\r", "_").Replace("\n\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 \n\r beautiful \n\t world";
         string replacedValue = Regex.Replace(testString, @"\n\r|\n\t", "_");
         Console.WriteLine(replacedValue);
         Console.ReadLine();
      }
   }
}

Output

The output of the above code is

Hello _ beautiful _ world
raja
Published on 08-Aug-2020 11:20:40
Advertisements