François Richard
François Richard

Reputation: 7055

Replace special character with unicode character in a string c#

Beginning in c#, haven't seen a duplicate. What I want to do is:

this string: İntersport transform to this string: \u0130ntersport

I found a way to convert everything in unicode but not to convert only the special character.

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]"

Upvotes: 1

Views: 3407

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

You can try using 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:

  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();

Upvotes: 6

Related Questions