【发布时间】:2012-07-15 07:05:40
【问题描述】:
我想通过 c# 将字符串中的更多 spaces 转换为  ?
如果字符串是
My name is this.
那么输出应该是
My name is this.
【问题讨论】:
标签: c#
我想通过 c# 将字符串中的更多 spaces 转换为  ?
如果字符串是
My name is this.
那么输出应该是
My name is this.
【问题讨论】:
标签: c#
将“常规”空格替换为“不间断空格”UTF-8 实体:
string outputString = "Input text".Replace(" ", "\u00A0");
【讨论】:
如果您需要将多个空格转换为单个不间断空格,请尝试使用 RegEx:
string convertedText =
new Regex("[ ]{2,}").Replace(textToConvert, " ");
例子:
我的名字是这个 ^ ^^^ ^将改为:
My Name is this
更新
如果您需要保留额外的空格(并且只用 nbsp 替换多个空格),您可以使用this regex:
string convertedText =
new Regex(" (?= )|(?<= ) ").Replace(textToConvert, " ");
例子:
我的名字是这个 ^ ^^^ ^将改为:
My Name is this
对于第二种情况,作为替代方案,您甚至可能根本不使用正则表达式(只是循环),但如果您必须经常使用相同的正则表达式,它们应该会更快。
【讨论】:
更正下一行无效
请使用 Server.HtmlEncode
你必须通过代码来完成
string s = " ";
if(s == " ")
{
s = " "
}
Or use "My name is this".Replace(" ", " ");
【讨论】:
试试这个
string myString = "My name is this".Replace(" ", " ");
【讨论】:
&nbsp;。你最终得到:“ ”、“ ”和“ ”