简体   繁体   中英

How to convert a space into non breaking space entity in c#

I want to convert more that spaces in a string to   through c#?

Like if string is

       My name  is this.

then output should be

   My name  is this.

用“非破坏空间”UTF-8实体替换“常规”空间:

string outputString = "Input text".Replace(" ", "\u00A0");

Try with RegEx if you need to convert multiple spaces to a single non-breaking-space :

string convertedText =
    new Regex("[ ]{2,}").Replace(textToConvert, " ");

Example:

My Name   is this
  ^    ^^^  ^

It'll be changed to:

My Name  is this

UPDATE
If you need to preserve extra spaces (and to replace with nbsp only multiple spaces) you may use this regex :

string convertedText =
    new Regex(" (?= )|(?<= ) ").Replace(textToConvert, "&nbsp;");

Example:

My Name   is this
  ^    ^^^  ^

It'll be changed to:

My Name&nbsp;&nbsp;&nbsp;is this

For the second case, as alternative, you may even do not use regex at all (just loop) but they should be faster if you have to do it often with the same regex.

Correction the line below will not work

Please use Server.HtmlEncode for it

You will have to do it by code

string s = " ";
if(s == " ")
{
 s = "&nbsp;"
}

Or use "My name  is this".Replace(" ", "&nbsp;");

尝试这个

string myString = "My name  is this".Replace("  ", " &nbsp;");

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