我想通过c#将字符串中spaces
的更多内容转换为
?
如果字符串是
My name is this.
然后输出
My name is this.
答案 0 :(得分:7)
替换"常规"空间与不间断的空间" UTF-8实体:
string outputString = "Input text".Replace(" ", "\u00A0");
答案 1 :(得分:6)
如果您需要将多个空格转换为单个非破坏空间,请尝试使用RegEx:
string convertedText =
new Regex("[ ]{2,}").Replace(textToConvert, " ");
示例:
My Name is this ^ ^^^ ^
它将改为:
My Name is this
<强>更新强>
如果您需要保留额外的空格(并且只需要替换多个空格),您可以使用this regex:
string convertedText =
new Regex(" (?= )|(?<= ) ").Replace(textToConvert, " ");
示例:
My Name is this ^ ^^^ ^
它将改为:
My Name is this
对于第二种情况,作为替代方案,您甚至可能根本不使用正则表达式(只是循环)但如果您必须经常使用相同的正则表达式,它们应该更快。
答案 2 :(得分:2)
更正下面的行不起作用
请使用Server.HtmlEncode
您必须通过代码
来完成string s = " ";
if(s == " ")
{
s = " "
}
Or use "My name is this".Replace(" ", " ");
答案 3 :(得分:1)
试试这个
string myString = "My name is this".Replace(" ", " ");