Replace Line Breaks in a String C#


Question

How can I replace Line Breaks within a string in C#?

1
473
10/26/2008 1:20:10 PM

Accepted Answer

Use replace with Environment.NewLine

myString = myString.Replace(System.Environment.NewLine, "replacement text")

As mentioned in other posts, if the string comes from another environment (OS) then you'd need to replace that particular environments implementation of new line control characters.

677
10/19/2014 11:43:29 AM

The solutions posted so far either only replace Environment.NewLine or they fail if the replacement string contains line breaks because they call string.Replace multiple times.

Here's a solution that uses a regular expression to make all three replacements in just one pass over the string. This means that the replacement string can safely contain line breaks.

string result = Regex.Replace(input, @"\r\n?|\n", replacementString);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon