简体   繁体   中英

How to replace char(10) [sql server] to something else in c#

Simple Question, the string im saving into my database uses char(10) to represent new line, i want to replace it with <br /> before saving it into the database so its displayed as an actual new line when i view it in a html page.

how im supposed to do that ? since there is no char(10) in c#

im using:

StringName.Replace("char(10)", "<br />");

which doesnt work.

my Code :

 var InscriptionText = Request["InscriptionText"];
InscriptionText.Replace("\n", "<br />");
var qry = "Instert into .." (normal query)
db.query(qry);

then i view the data in the databse to find that it didnt replace it and its saved as "line1line2line3line4"

Replace method returns a new string, you need to save it.

Just change the second line:

var InscriptionText = Request["InscriptionText"];
InscriptionText = InscriptionText.Replace("\n", "<br />");
//...

But, I would suggest you not to edit the actual user input. Save it as it comes to you. And replace it while showing it back to user. Just a suggestion!

In c# you could do this:

string breakText1 = "Some text without a line break.";
string breakText2 = "Some text " + Environment.NewLine + "with a line break.";
string breakText3 = "Some text \nwith a new line.";
string breakText4 = "Some text \rwith a carriage return.";

Console.WriteLine("Strings before replace...");
Console.WriteLine(breakText1);
Console.WriteLine(breakText2);
Console.WriteLine(breakText3);
Console.WriteLine(breakText4);

Console.WriteLine("Strings after replace...");
Console.WriteLine(breakText1.Replace("\r\n", "<br />").Replace("\r", "<br />").Replace("\n", "<br />").Replace("<br /><br />", "<br />"));
Console.WriteLine(breakText2.Replace("\r\n", "<br />").Replace("\r", "<br />").Replace("\n", "<br />").Replace("<br /><br />", "<br />"));
Console.WriteLine(breakText3.Replace("\r\n", "<br />").Replace("\r", "<br />").Replace("\n", "<br />").Replace("<br /><br />", "<br />"));
Console.WriteLine(breakText4.Replace("\r\n", "<br />").Replace("\r", "<br />").Replace("\n", "<br />").Replace("<br /><br />", "<br />"));

Of course, this could be done much more elegantly, but this gets the idea across and covers the different common combinations of Carriage Return and/or Line Feed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM