4 回答

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超8個(gè)贊
當(dāng)您將字符串附加到 StringBuilder 時(shí),所有轉(zhuǎn)義字符都將被刪除。您可以執(zhí)行以下操作來保留它們。
var sb = new StringBuilder();
var html = "<span style=\"background-color: red;color:white;\">\\r</span>";
sb.Append(html);
請(qǐng)注意,我已更改\r為\\r.
輸出
當(dāng)您嘗試打電話時(shí)sb.ToString()
<span style="background-color: red;color:white;">\r</span>

TA貢獻(xiàn)1841條經(jīng)驗(yàn) 獲得超3個(gè)贊
有用
var someString = @"Chunk1 \r\n Chunk2";
var color = "red";
var colorizedOutput = new StringBuilder();
foreach (var ch in someString.ToCharArray())
{
var concreteChar = ch == ' ' ? " " : ch.ToString();
var htmlSpan = "<span " + "style=" + '"' + $"background-color: {color};" + "color:white;" + '"' + ">" + concreteChar + "</span>"+"\n";
colorizedOutput.Append(htmlSpan);
}
Console.WriteLine(colorizedOutput.ToString());

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以將 htmlspan 簡(jiǎn)化為
string htmlSpan = $"<span style='background-color: {color};color:white;>{concreteChar}</span>";
這將解決您的問題。

TA貢獻(xiàn)1993條經(jīng)驗(yàn) 獲得超6個(gè)贊
只需使用 Environment.NewLine 屬性
就像是
StringBuilder colorizedOutput = new StringBuilder();
colorizedOutput.AppendFormat("<span style=\"background-color: red;color:white;\">{0}
</span>", Environment.NewLine);
string s = sb.ToString();
- 4 回答
- 0 關(guān)注
- 290 瀏覽
添加回答
舉報(bào)