How to Replace Line Breaks (\r\n, \n) in C# Strings
Learn to replace newlines like \r\n or \n in C# strings using ReplaceLineEndings, Regex.Replace, or chained methods. Handle cross-platform text from files or APIs with code examples and pitfalls.
How to replace line breaks (newlines like \r\n or \n) in a string in C#?
To replace line breaks like \r\n or \n in a C# string, use String.ReplaceLineEndings() in .NET 6+ for a clean, one-shot fix that handles all variants (CRLF, LF, CR) and swaps them with Environment.NewLine or custom text. For older .NET versions or more control, chain Replace("\r\n", ""), Replace("\n", ""), and Replace("\r", ""), or lean on Regex.Replace(input, @"\r\n?|\n", "replacement") to catch everything efficiently. Why bother normalizing? Cross-platform text from files or APIs often mixes these, leading to mangled output unless you handle it right.
Contents
- How to Replace Line Breaks in a C# String
- Line Break Symbols Explained
- Using ReplaceLineEndings for All Newlines
- Regex Method for Flexible Replacement
- Common Pitfalls and Cross-Platform Tips
- Alternatives and Related Scenarios
- Sources
- Conclusion
How to Replace Line Breaks in a C# String
Ever pulled text from a file, web API, or user input and watched it turn into a jumbled mess because of mismatched newlines? In C#, replacing line breaks in a string is straightforward once you pick the right tool. The modern go-to is string.ReplaceLineEndings(replacement), available since .NET 6—it scans for every possible newline flavor and swaps them out in a single pass.
Here’s a quick example to replace newlines with a space:
using System;
string input = "Line one\r\nLine two\nLine three\r";
string normalized = input.ReplaceLineEndings(" "); // Output: "Line one Line two Line three "
Console.WriteLine(normalized);
This beats older hacks because it covers Unicode newlines too (like NEL or LS), not just the basics. Performance-wise, it’s O(n), so no sweat for real-world strings. But if you’re stuck on .NET 5 or earlier? Jump to the regex section—it’s a lifesaver.
And yeah, Environment.NewLine is your friend here. On Windows, it’s \r\n; on Linux/macOS, just \n. Let the runtime handle the platform guesswork.
Line Break Symbols Explained
What even are these sneaky characters causing chaos? Most folks know \n (line feed, Unix-style) and \r\n (carriage return + line feed, Windows), but old Macs used solo \r. Throw in web HTML (<br> isn’t a char, but \n often sneaks in), and you’ve got a recipe for bugs.
Break it down:
| Symbol | Char Codes | Common Source | Notes |
|---|---|---|---|
\r\n |
13 + 10 | Windows files, HTTP | Standard CRLF |
\n |
10 | Unix/Linux, JSON | LF only |
\r |
13 | Legacy Mac | Rare now |
\u0085 (NEL) |
133 | Some Unicode | Edge case |
Environment.NewLine dynamically picks the right one for your OS—smart, right? Test it: Console.WriteLine(Environment.NewLine.Length); spits out 2 on Windows, 1 elsewhere. According to the official .NET docs, ignoring these leads to “canonicalization” issues in text processing.
Pro tip: Log your input with input.Replace("\r", "\\r").Replace("\n", "\\n") to visualize the mess before fixing.
Using ReplaceLineEndings for All Newlines
Introduced in .NET 6, ReplaceLineEndings is Microsoft’s gift to string wranglers. It normalizes all newline sequences—\r\n, \n, \r, next-line (NEL), line-separator (LS), etc.—to whatever you specify.
Basic usage:
string messyText = "Hello\r\nWorld\nFoo\rBar";
string fixedText = messyText.ReplaceLineEndings(Environment.NewLine); // Ensures consistent OS newlines
// Or custom: messyText.ReplaceLineEndings(" | ");
The Microsoft Learn page calls it out as the efficient way to handle imported text. Default? It uses Environment.NewLine. Pass "" to strip them entirely, or " | " for pipe-separated logs.
But heads up: Skip it for strict protocols like HTTP, where \r\n is non-negotiable. Runs in linear time, immutable (returns new string), and thread-safe. Upgrade if you can—saves headaches.
What if your replacement has newlines? It preserves them intact. Neat.
Regex Method for Flexible Replacement
Need to replace line breaks with a space, comma, or anything wild? Regex shines here, especially pre-.NET 6 or for patterns like multiple consecutive newlines.
The pattern @"\r\n?|\n" greedily matches CRLF, lone CR, or LF without backtracking drama:
using System.Text.RegularExpressions;
string input = "Apple\r\nBanana\nCherry\r";
string result = Regex.Replace(input, @"\r\n?|\n", ", "); // "Apple, Banana, Cherry"
This powers through mixed sources like pasted clipboard text or CSV imports. From a popular Stack Overflow thread, devs swear by it for single-pass efficiency over chained Replace calls, which can bloat if you hit many variants.
Tweak for extras: @"\r\n?|\n|\r" if paranoid about solo CR. Compiled regex? Regex.Replace(input, pattern, repl, RegexOptions.Compiled) for hot loops. And for collapsing multiples: @"\r\n?|\n\r?\s*" then trim.
Regex costs a tad more upfront but scales better than multiple string ops. You might wonder—why not always use it? Simplicity wins for basics.
Common Pitfalls and Cross-Platform Tips
Cross-platform apps? Newlines bite hard. A Windows-built string with \r\n on Linux looks doubled. Always normalize incoming data.
Pitfalls I’ve seen:
- Chaining blindly:
Replace("\n", "").Replace("\r", "")misses\r\norder. Fix:\r\nfirst. - Hardcoding: Don’t
Replace("\\n", "")—that’s literal backslash-n, not newline. - Performance: 1M-line strings? Regex or ReplaceLineEndings only.
- Encoding: UTF-8 files might hide Unicode newlines.
Cross-platform code snippet:
public static string NormalizeNewlines(string input, string replacement = null)
{
replacement ??= Environment.NewLine;
return input.ReplaceLineEndings(replacement); // .NET 6+
// Fallback:
// return Regex.Replace(input, @"\r\n?|\n|\r", replacement);
}
As noted in Stack Overflow discussions, test on both OSes. Unit test with "\r\n".ReplaceLineEndings("") == "".
Edge case: Empty strings or pure newlines? They return empty. Good.
Alternatives and Related Scenarios
Beyond basics, what about reversing it—replacing spaces with newlines? input.Replace(" ", Environment.NewLine) does it, but watch for multiples.
Or stripping entirely: input.ReplaceLineEndings(""). For HTML: Regex.Replace(input, "<br\\s*/?>|\\r\\n?|\\n", " ").
In files: File.ReadAllText(path).ReplaceLineEndings("\n") for Unix output. Excel/Notepad imports? Same regex trick.
Chained fallback for ancient .NET:
input.Replace("\r\n", replacement)
.Replace("\r", replacement)
.Replace("\n", replacement);
Scales to trimming extras: .Trim(Environment.NewLine.ToCharArray()). Covers most “replace newline with comma” or “remove line breaks” needs.
Sources
- String.ReplaceLineEndings — Official .NET API for replacing all newline sequences efficiently: https://learn.microsoft.com/en-us/dotnet/api/system.string.replacelineendings?view=net-8.0
- Replace line breaks in a string C# — Stack Overflow thread with regex and chained replace solutions: https://stackoverflow.com/questions/238002/replace-line-breaks-in-a-string-c-sharp
Conclusion
Replacing line breaks in C# boils down to ReplaceLineEndings() for modern simplicity or regex for power and legacy support—pick based on your .NET version and needs. Normalize early to dodge platform pitfalls, test with mixed inputs, and lean on Environment.NewLine for portability. You’ll end up with clean, predictable strings every time, whether processing files, APIs, or user junk.
Use String.ReplaceLineEndings() to replace line breaks in C# strings efficiently. This .NET method (O(n) complexity) replaces all newline sequences like \r\n, \n, \r, NEL, LS, FF, PS with Environment.NewLine (CRLF on Windows, LF on Unix) or a custom replacementText. For example, myString.ReplaceLineEndings(" | ") handles line break symbols from any source. Avoid in protocol parsers like HTTP due to mandated CRLF. Equivalent to ReplaceLineEndings(Environment.NewLine) for canonicalization.
To replace line breaks, call myString.Replace(Environment.NewLine, "replacement text") for platform-specific handling like Windows \r\n. This simple chained method works if input matches the current OS newline. Combine with checks for cross-platform sources, as Environment.NewLine adapts to the runtime environment, making it ideal for line break code in C# apps.
For robust replace line breaks with space or any text, use Regex.Replace(input, @"\r\n?|\n", replacementString). This single-pass regex catches \r\n, \r, \n variants safely, even if replacement contains newlines, outperforming multiple string.Replace calls. Perfect for handling line break symbols from mixed sources like files or HTML.
In .NET 6+, myString.ReplaceLineEndings() directly replaces line breaks with Environment.NewLine, covering all sequences (CRLF, LF, CR, etc.). Use ReplaceLineEndings(customText) for specifics like replace line breaks with space. This modern method simplifies line break code without manual chaining.
Chain replaces to remove line breaks: input.Replace("\r\n", "").Replace("\n", "").Replace("\r", "") covers Windows, Unix, and old Mac variants. Extend for replacing spaces with newlines by reversing logic. Reliable fallback before .NET 6 for cross-platform text processing.
