简体   繁体   English

将特殊字符替换为字符串C#中的Unicode字符

[英]Replace special character with unicode character in a string c#

Beginning in c#, haven't seen a duplicate. 从C#开始,还没有看到任何重复。 What I want to do is: 我想做的是:

this string: İntersport transform to this string: \İntersport 此字符串: İntersport转换为此字符串: \İntersport

I found a way to convert everything in unicode but not to convert only the special character. 我找到了一种方法来转换unicode中的所有内容,而不是仅转换特殊字符。

thanks in advance for your help 在此先感谢您的帮助

edit: 编辑:

I have tried your solution: 我已经尝试过您的解决方案:

 string source = matchedWebIDDest.name;
 string parsedNameUnicode = string.Concat(source.Select(c => c < 32 || c > 255 ? "\\u" + ((int)c).ToString("x4") : c.ToString()));

But I get : "System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Syst‌​em.Char,System.Strin‌​g]" 但是我得到:“ System.Linq.Enumerable + WhereSelectEnumerableIterator`2 [System.Char.System,Strin.g]”

You can try using Linq : 您可以尝试使用Linq

  using System.Linq;

  ...

  string source = "İntersport";

  // you may want to change 255 into 127 if you want standard ASCII table
  string target = string.Concat(source
    .Select(c => c < 32 || c > 255  
       ? "\\u" + ((int)c).ToString("x4") // special symbol: command one or above Ascii 
       : c.ToString()));                 // within ascii table [32..255]

  // \u0130ntersport
  Console.Write(target);

Edit: No Linq solution: 编辑:没有Linq解决方案:

  string source = "İntersport";

  StringBuilder sb = new StringBuilder();

  foreach (char c in source) 
    if (c < 32 || c > 255)
      sb.Append("\\u" + ((int)c).ToString("x4"));
    else
      sb.Append(c);

  string target = sb.ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM