Replace Line Breaks in a String C#

Replace Line Breaks in a String C#

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.

Replace Next Line by br in the String Obtained from TextBox

string.Replace returns a string. Do this:

string text= textbox.Text;
text = text.Replace(System.Environment.NewLine, "<br>"); //note the text = ...

You are almost there, except what you do in your code isn't returning the result of your string.Replace.

How to eliminate ALL line breaks in string?

Below is the extension method solving my problem. LineSeparator and ParagraphEnding can be of course defined somewhere else, as static values etc.

public static string RemoveLineEndings(this string value)
{
if(String.IsNullOrEmpty(value))
{
return value;
}
string lineSeparator = ((char) 0x2028).ToString();
string paragraphSeparator = ((char)0x2029).ToString();

return value.Replace("\r\n", string.Empty)
.Replace("\n", string.Empty)
.Replace("\r", string.Empty)
.Replace(lineSeparator, string.Empty)
.Replace(paragraphSeparator, string.Empty);
}

Replace text which contain line breaks without dropping them

You can use Regex to find any kind of whitespace. This includes regular spaces but also carriage returns and linefeeds as well as tabulators or half-spaces and so on.

string input = @"This is text
i want
to keep
but
Replace this sentence
because i dont like it.";

string dontLike = @"Replace this sentence because i dont like it.";
string pattern = Regex.Escape(dontLike).Replace(@"\ ", @"\s+");

Console.WriteLine("Pattern:");
Console.WriteLine(pattern);

string clean = Regex.Replace(input, pattern, "");

Console.WriteLine();
Console.WriteLine("Result:");
Console.WriteLine(clean);
Console.ReadKey();

Output:

Pattern:
Replace\s+this\s+sentence\s+because\s+i\s+dont\s+like\s+it\.

Result:
This is text
i want
to keep
but

Regex.Escape escapes any character that would otherwise have a special meaning in Regex. E.g., the period "." means "any number of repetitions". It also replaces the spaces " " with @"\ ". We in turn replace @"\ " in the search pattern by @"\s+". \s+ in Regex means "one or more white spaces".

C# string replace , with a linebreak (Enter)


yourString = yourString.Replace(",", System.Environment.NewLine);

Demo here https://dotnetfiddle.net/M2lBKS

How to remove new line characters from a string?

I like to use regular expressions. In this case you could do:

string replacement = Regex.Replace(s, @"\t|\n|\r", "");

Regular expressions aren't as popular in the .NET world as they are in the dynamic languages, but they provide a lot of power to manipulate strings.

C# remove carriage returns, line breaks and whitespaces from string as efficient as possible (benchmark)

The term "efficiently" can heavily depend on your actual strings and number of them. I've come up with next benchmark (for BenchmarkDotNet) :

public class Replace
{
private static readonly string S = " ab c\r\n de.\nf";
private static readonly Regex Reg = new Regex(@"\s+", RegexOptions.Compiled);

[Benchmark]
public string SimpleReplace() => S
.Replace(" ","")
.Replace("\\r","")
.Replace("\\n","");

[Benchmark]
public string StringBuilder() => new StringBuilder().Append(S)
.Replace(" ","")
.Replace("\\r","")
.Replace("\\n","")
.ToString();

[Benchmark]
public string RegexReplace() => Reg.Replace(S, "");

[Benchmark]
public string NewString()
{
var arr = new char[S.Length];
var cnt = 0;
for (int i = 0; i < S.Length; i++)
{
switch(S[i])
{
case ' ':
case '\r':
case '\n':
break;

default:
arr[cnt] = S[i];
cnt++;
break;
}
}

return new string(arr, 0, cnt);
}

[Benchmark]
public string NewStringForeach()
{
var validCharacters = new char[S.Length];
var next = 0;

foreach(var c in S)
{
switch(c)
{
case ' ':
case '\r':
case '\n':
// Ignore then
break;

default:
validCharacters[next++] = c;
break;
}
}

return new string(validCharacters, 0, next);
}
}

This gives on my machine:

|          Method |        Mean |     Error |    StdDev |
|---------------- |------------:|----------:|----------:|
| SimpleReplace | 122.09 ns | 1.273 ns | 1.063 ns |
| StringBuilder | 311.28 ns | 6.313 ns | 8.850 ns |
| RegexReplace | 1,194.91 ns | 23.376 ns | 34.265 ns |
| NewString | 52.26 ns | 1.122 ns | 1.812 ns |
|NewStringForeach | 40.04 ns | 0.877 ns | 1.979 ns |

Replace \\n with \n in a string in C#

What you really want to replace is a backslash followed by the letter n with the newline character

string.Replace("\\n","\n");

The reason Replace("\\","\") gives that compilation error is because the backslash is escaping the double quote so the string continues on to the end of the line which is not allowed unless it's a verbatim string (starts with an @).

replacing carriage returns with breaks in a string for html asp.net

Replace doesn't perform the operation in place. The method instead returns a new instance of the modified string.

Your code doesn't store that returned value anywhere. Try setting the message variable like this:

string message = txtbxEmailBody.Text
.Replace(Environment.NewLine, "<br />")
.Replace("\n", "<br />")
.Replace("\r", "<br />");


Related Topics



Leave a reply



Submit