Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Replace(char, char) method in C#

Tags:

string

c#

How do I replace \n with empty space?

I get an empty literal error if I do this:

string temp = mystring.Replace('\n', ''); 
like image 364
sarsnake Avatar asked Mar 16 '09 18:03

sarsnake


2 Answers

String.Replace('\n', '') doesn't work because '' is not a valid character literal.

If you use the String.Replace(string, string) override, it should work.

string temp = mystring.Replace("\n", ""); 
like image 68
Samuel Avatar answered Sep 29 '22 16:09

Samuel


As replacing "\n" with "" doesn't give you the result that you want, that means that what you should replace is actually not "\n", but some other character combination.

One possibility is that what you should replace is the "\r\n" character combination, which is the newline code in a Windows system. If you replace only the "\n" (line feed) character it will leave the "\r" (carriage return) character, which still may be interpreted as a line break, depending on how you display the string.

If the source of the string is system specific you should use that specific string, otherwise you should use Environment.NewLine to get the newline character combination for the current system.

string temp = mystring.Replace("\r\n", string.Empty); 

or:

string temp = mystring.Replace(Environment.NewLine, string.Empty); 
like image 23
Guffa Avatar answered Sep 29 '22 18:09

Guffa