How can I replace Line Breaks within a string in C#?
-
2Please tell us more: what is a "line break" to you? What do you want to replace them with? – Jay Bazuzi Oct 26 '08 at 13:55
-
ha ha .I was checking the same for in java when i found out System.getProperty("line.separator") was curios to know the counterpart in C#. your post helped me . – Ravisha Sep 29 '10 at 04:49
-
possible duplicate of [What would be the fastest way to remove Newlines from a String in C#?](http://stackoverflow.com/questions/25349/what-would-be-the-fastest-way-to-remove-newlines-from-a-string-in-c) – Ray Jan 19 '11 at 18:56
20 Answers
Use replace with Environment.NewLine
myString = myString.Replace(System.Environment.NewLine, "replacement text"); //add a line terminating ;
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.

- 9,141
- 22
- 109
- 221

- 17,718
- 10
- 37
- 39
-
8First it didn't work for me. After some research, I found the solution: I had to use 'using System;' or 'System.Environment.NewLine' – Smolla Feb 27 '12 at 16:47
-
14Did not remove all the newline chars. Try this string **"\n \r\nMy message \r\n \n \r\n is this.\n \n \r\n"** – Shakti Prakash Singh Aug 04 '13 at 12:12
-
19In general, I like this solution. However, do note that even on the same OS, the actual newlines may not match. This happened to me why processing returned SQL. The new lines were \n, while Environment.NewLine was \r\n. The result was that nothing was matched so the new lines remained. – Dono Oct 02 '13 at 03:06
-
@Dono > where does the SQL data come from ? Probably from an outside source dealing with new lines the UNIX way. That's a problem with the data format, not with OS or this method... – Laurent S. Nov 26 '13 at 14:50
-
1This should be one of the static methods of the String class. .NET itself should be able to detect format of source line breaks in a string and convert it to Environment.NewLine \r\n format... – Dean Kuga Apr 06 '18 at 20:48
-
Use CSS instead of exposing yourself to XSS vulnerabilities. ```@Model.CommentText``` – Mike Olund May 13 '19 at 19:05
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);

- 811,555
- 193
- 1,581
- 1,452
-
3so your saying doing Regex.Replace(input, @"[\r\n]+", replacementString) wouldn't accomplish the same task? – flamebaud Jun 26 '13 at 11:44
-
10@flamebaud No, that would produce a different result if there are multiple line breaks in a row. "\r\n?|\n" would replace each line break while "[\r\n]+" would do a single replace for any number of line breaks. – David Hammond Sep 09 '14 at 18:09
-
1
-
4This is actually the correct solution if you want to remove line break in a string that may come from different OS. Good example is JSON formatting. +1 – Bastien Vandamme Oct 07 '16 at 02:12
-
You shouldn't use verbatim string (@ prefix) for your regex as the `\r\n` is escaped – Mikhail Dec 06 '16 at 14:06
-
-
1If the verbatim string (@ prefix) is not used, then you would need to have two backslashes in a row everywhere it is used, so the answer by @mark_byers above is still correct. The @ prefix makes it so that the backslash is part of the string which it must be for Regex to use it as the escape character. – Kirk Liemohn Sep 11 '17 at 16:47
-
It would be appreciated if someone edited this answer and added some of these comment with info. I can't get my head around regex, yet I need more regex samples to test on. – Bizhan Dec 17 '17 at 11:42
-
Nevermind, I was trying this inside an interpolated string. You can't use double quotes in one. – PRMan Jul 06 '18 at 23:21
-
1string result = System.Text.RegularExpressions.Regex.Replace(plainText, @"\r\n?|\n", ""); to fix any compiler errors. – Dymas Aug 02 '19 at 20:51
To extend The.Anyi.9's answer, you should also be aware of the different types of line break in general use. Dependent on where your file originated, you may want to look at making sure you catch all the alternatives...
string replaceWith = "";
string removedBreaks = Line.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
should get you going...

- 29,603
- 12
- 67
- 114
-
6First i liked the environment thingi better, but if the String doesnt come from the system its running on, it wont work. +1 – Flo Nov 17 '11 at 10:21
-
This solution dint work for me when i tried to use it to replace newline in powershell output from C#. Replace(System.Environment.NewLine,"") worked for me. – Ram Feb 04 '13 at 03:27
-
1isn't `Line.Replace("\n", replaceWith).Replace("\r", replaceWith);` enough? – Thomas Ayoub Jul 22 '15 at 15:38
-
6No, because if you have `\r\n` you will end up with the replacement string twice - not ideal. – ZombieSheep Jul 22 '15 at 17:02
-
2Don't you need string literals? string removedBreaks = Line.Replace(@"\r\n", replaceWith).Replace(@"\n", replaceWith).Replace(@"\r", replaceWith); – Shawn Dotey Mar 13 '17 at 13:42
-
3@ShawnDotey no need to, we want to replace control characters, not sequences of backslash and letter. – N. Kudryavtsev Oct 05 '18 at 10:31
I would use Environment.Newline when I wanted to insert a newline for a string, but not to remove all newlines from a string.
Depending on your platform you can have different types of newlines, but even inside the same platform often different types of newlines are used. In particular when dealing with file formats and protocols.
string ReplaceNewlines(string blockOfText, string replaceWith)
{
return blockOfText.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
}

- 339,232
- 124
- 596
- 636
-
This is the only thing that worked for me when I wanted to collapse a retrieved web page code to a single line (for making regex patterns easier). – Paw Baltzersen Jul 17 '11 at 19:09
-
Totally agree with Brian R. Bondy. The solution offered by Corin and upvoted so much is very naive, at least. – Califf Mar 29 '13 at 21:33
Use new in .NET 6 method
myString = myString.ReplaceLineEndings();
Replaces ALL newline sequences in the current string.
Documentation: ReplaceLineEndings

- 351
- 3
- 4
-
1Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 17 '22 at 07:23
-
4
-
1Do note that there is a overload of the shown method that takes a String parameter to replace with. Otherwise is just replaces newlines with `Environment.NewLine` - which might what is needed sometimes :) – Nicolai Krüger Jan 13 '23 at 09:17
If your code is supposed to run in different environments, I would consider using the Environment.NewLine
constant, since it is specifically the newline
used in the specific environment.
line = line.Replace(Environment.NewLine, "newLineReplacement");
However, if you get the text from a file originating on another system, this might not be the correct answer, and you should replace with whatever newline constant is used on the other system. It will typically be \n
or \r\n
.

- 8,951
- 5
- 30
- 47

- 161,458
- 45
- 265
- 341
-
You need to reassign it back to the original variable as replacement doesn't occur in place. – tvanfosson Oct 26 '08 at 16:14
-
@driss I would like to know how would you pick a right new line constant when you have no idea what system a file came from... this solution truly seems to be UNIVERSAL. – Califf Mar 29 '13 at 21:36
if you want to "clean" the new lines, flamebaud comment using regex @"[\r\n]+"
is the best choice.
using System;
using System.Text.RegularExpressions;
class MainClass {
public static void Main (string[] args) {
string str = "AAA\r\nBBB\r\n\r\n\r\nCCC\r\r\rDDD\n\n\nEEE";
Console.WriteLine (str.Replace(System.Environment.NewLine, "-"));
/* Result:
AAA
-BBB
-
-
-CCC
DDD---EEE
*/
Console.WriteLine (Regex.Replace(str, @"\r\n?|\n", "-"));
// Result:
// AAA-BBB---CCC---DDD---EEE
Console.WriteLine (Regex.Replace(str, @"[\r\n]+", "-"));
// Result:
// AAA-BBB-CCC-DDD-EEE
}
}

- 18,382
- 2
- 44
- 54
-
-
Thanks for this useful sample code. I was fixed via this sytnax: Regex.Replace(str, @"[\r\n]+", "-") – Sedat Kumcu Apr 19 '20 at 23:01
-
Don't forget that replace doesn't do the replacement in the string, but returns a new string with the characters replaced. The following will remove line breaks (not replace them). I'd use @Brian R. Bondy's method if replacing them with something else, perhaps wrapped as an extension method. Remember to check for null values first before calling Replace or the extension methods provided.
string line = ...
line = line.Replace( "\r", "").Replace( "\n", "" );
As extension methods:
public static class StringExtensions
{
public static string RemoveLineBreaks( this string lines )
{
return lines.Replace( "\r", "").Replace( "\n", "" );
}
public static string ReplaceLineBreaks( this string lines, string replacement )
{
return lines.Replace( "\r\n", replacement )
.Replace( "\r", replacement )
.Replace( "\n", replacement );
}
}

- 524,688
- 99
- 697
- 795
-
can't have `''` in C# - there is no such thing as an empty char. will `'\0'` work instead? – Shevek Jun 25 '10 at 13:02
-
1@Shevek -- just used the wrong quotes. Must have been doing a fair amount of javascript the day I answered this. – tvanfosson Jun 25 '10 at 13:25
-
-
2the mistake you made here just proves it IS better. Most companies I worked for have it their the coding standard - DO NOT USE HARDCODED LITERALS. – Califf Feb 03 '13 at 23:50
-
2@Califf the "mistake" I made wouldn't have been made in an IDE with Intellisense nor would it have compiled. If you feel that `string.Empty` is better, by all means use it. – tvanfosson Feb 04 '13 at 04:10
To make sure all possible ways of line breaks (Windows, Mac and Unix) are replaced you should use:
string.Replace("\r\n", "\n").Replace('\r', '\n').Replace('\n', 'replacement');
and in this order, to not to make extra line breaks, when you find some combination of line ending chars.

- 763
- 10
- 22
Why not both?
string ReplacementString = "";
Regex.Replace(strin.Replace(System.Environment.NewLine, ReplacementString), @"(\r\n?|\n)", ReplacementString);
Note: Replace strin
with the name of your input string.

- 8,539
- 4
- 63
- 74

- 2,201
- 2
- 19
- 18
I needed to replace the \r\n
with an actual carriage return and line feed and replace \t
with an actual tab. So I came up with the following:
public string Transform(string data)
{
string result = data;
char cr = (char)13;
char lf = (char)10;
char tab = (char)9;
result = result.Replace("\\r", cr.ToString());
result = result.Replace("\\n", lf.ToString());
result = result.Replace("\\t", tab.ToString());
return result;
}

- 10,042
- 11
- 48
- 64

- 71
- 1
- 2
var answer = Regex.Replace(value, "(\n|\r)+", replacementString);

- 13,577
- 3
- 35
- 40
-
Your answer is missing the '@' character, before the regular expression. – Tatami Dec 16 '21 at 07:06
As new line can be delimited by \n
, \r
and \r\n
, first we’ll replace \r
and \r\n
with \n
, and only then split data string.
The following lines should go to the parseCSV
method:
function parseCSV(data) {
//alert(data);
//replace UNIX new lines
data = data.replace(/\r\n/g, "\n");
//replace MAC new lines
data = data.replace(/\r/g, "\n");
//split into rows
var rows = data.split("\n");
}
Best way to replace linebreaks safely is
yourString.Replace("\r\n","\n") //handling windows linebreaks
.Replace("\r","\n") //handling mac linebreaks
that should produce a string with only \n (eg linefeed) as linebreaks. this code is usefull to fix mixed linebreaks too.

- 2,563
- 1
- 21
- 25
Use the .Replace() method
Line.Replace("\n", "whatever you want to replace with");

- 43,474
- 48
- 123
- 161
Another option is to create a StringReader
over the string in question. On the reader, do .ReadLine()
in a loop. Then you have the lines separated, no matter what (consistent or inconsistent) separators they had. With that, you can proceed as you wish; one possibility is to use a StringBuilder
and call .AppendLine
on it.
The advantage is, you let the framework decide what constitutes a "line break".

- 60,409
- 11
- 110
- 181
string s = Regex.Replace(source_string, "\n", "\r\n");
or
string s = Regex.Replace(source_string, "\r\n", "\n");
depending on which way you want to go.
Hopes it helps.
If you want to replace only the newlines:
var input = @"sdfhlu \r\n sdkuidfs\r\ndfgdgfd";
var match = @"[\\ ]+";
var replaceWith = " ";
Console.WriteLine("input: " + input);
var x = Regex.Replace(input.Replace(@"\n", replaceWith).Replace(@"\r", replaceWith), match, replaceWith);
Console.WriteLine("output: " + x);
If you want to replace newlines, tabs and white spaces:
var input = @"sdfhlusdkuidfs\r\ndfgdgfd";
var match = @"[\\s]+";
var replaceWith = "";
Console.WriteLine("input: " + input);
var x = Regex.Replace(input, match, replaceWith);
Console.WriteLine("output: " + x);

- 6,350
- 5
- 52
- 67
This is a very long winded one-liner solution but it is the only one that I had found to work if you cannot use the the special character escapes like "\r"
and "\n"
and \x0d
and \u000D
as well as System.Environment.NewLine
as parameters to thereplace()
method
MyStr.replace( System.String.Concat( System.Char.ConvertFromUtf32(13).ToString(), System.Char.ConvertFromUtf32(10).ToString() ), ReplacementString );
This is somewhat offtopic but to get it to work inside Visual Studio's XML .props files, which invoke .NET via the XML properties, I had to dress it up like it is shown below.
The Visual Studio XML --> .NET environment just would not accept the special character escapes like "\r"
and "\n"
and \x0d
and \u000D
as well as System.Environment.NewLine
as parameters to thereplace()
method.
$([System.IO.File]::ReadAllText('MyFile.txt').replace( $([System.String]::Concat($([System.Char]::ConvertFromUtf32(13).ToString()),$([System.Char]::ConvertFromUtf32(10).ToString()))),$([System.String]::Concat('^',$([System.Char]::ConvertFromUtf32(13).ToString()),$([System.Char]::ConvertFromUtf32(10).ToString())))))

- 303
- 9
Based on @mark-bayers answer and for cleaner output:
string result = Regex.Replace(ex.Message, @"(\r\n?|\r?\n)+", "replacement text");
It removes \r\n
, \n
and \r
while perefer longer one and simplify multiple occurances to one.

- 3,520
- 24
- 29