【问题标题】:How to replace char(10) [sql server] to something else in c#如何将 char(10) [sql server] 替换为 c# 中的其他内容
【发布时间】:2016-08-18 02:48:03
【问题描述】:

简单问题,我保存到我的数据库中的字符串使用 char(10) 来表示新行,我想在将其保存到数据库之前将其替换为 <br />,以便在我查看它时显示为实际的新行在 html 页面中。

我应该怎么做?因为c#中没有char(10)

我正在使用:

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

这不起作用。

我的代码:

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

然后我查看数据库中的数据发现它没有替换它并保存为“line1line2line3line4”

【问题讨论】:

  • 你的意思是char(10) = '\n'?为什么不StringName = StringName.Replace("\n", "&lt;br /&gt;");
  • 你怎么说doesnt work?显示代码你是如何使用它的。
  • 当我在更新查询中使用“\n”时,它不起作用,但 char(10) 工作正常,我在 c# 中也尝试过 \n,但没有用。
  • 请分享不起作用的代码,我们怎么能假设你在写什么?
  • Replace 方法返回一个新字符串,您也需要捕获它。只需将第二行更改为InscriptionText = InscriptionText.Replace("\n", "&lt;br /&gt;");

标签: c# sql-server replace newline


【解决方案1】:

Replace 方法返回一个新字符串,需要保存。

只需更改第二行:

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

但是,我建议您不要编辑实际的用户输入。保存它,因为它涉及到你。并在向用户展示时替换它。只是一个建议!

【讨论】:

    【解决方案2】:

    在 c# 中你可以这样做:

    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 />"));
    

    当然,这可以更优雅地完成,但这可以理解并涵盖回车和/或换行的不同常见组合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-10
      • 2020-04-01
      • 2020-03-13
      • 2011-11-10
      • 1970-01-01
      • 2011-07-02
      相关资源
      最近更新 更多