21

Possible Duplicate:
Converting Unicode strings to escaped ascii string

How can I convert ä... into something like \u0131... ?

is there any Function for doing this ?

p.s :

beside this way : [ sorry @Kendall Frey :-)]

char a = 'ä';
string escape = "\\u" + ((int)a).ToString("X").PadLeft(4, '0');
5
  • @JonSkeet isn't there any READY function ? Commented Nov 8, 2012 at 14:54
  • 7
    It's ready for you to cut and paste... Commented Nov 8, 2012 at 14:55
  • also string.isNullOrEmpty code can be cut and paste , my question is regarding a ready one like string.isNullOrEmpty Commented Nov 8, 2012 at 14:56
  • 2
    @RoyiNamir There is. I wrote it for you. Commented Nov 8, 2012 at 14:58
  • 1
    Your answer is "no". There is no built-in function for this. You'll have to use @KendallFrey's solution. Commented Nov 8, 2012 at 15:00

2 Answers 2

30

Here's a function to convert a char to an escape sequence:

string GetEscapeSequence(char c)
{
    return "\\u" + ((int)c).ToString("X4");
}

It isn't gonna get much better than a one-liner.

And no, there's no built-in function as far as I know.

Sign up to request clarification or add additional context in comments.

8 Comments

I suspect there's a way of getting the left-padding correct in the format string instead of calling PadLeft though...
@JonSkeet -- I believe just changing to ToString("X4") and dropping the PadLeft will do the trick.
Fine. But I thought of it first :P
Mostly for fun: var s = "ä"; s = new string(s.SelectMany(c => (int)c > 127 ? ("\\u" + ((int)c).ToString("X4")).ToArray() : new char[] { c }).ToArray());
2019 edition: string EscapeSequence(char c) => $@"\u{(int)c:X4}";
|
9

There is no built-in function AFAIK. Here is one pretty silly solution that works. But Kendall Frey provided much better variant.

string GetUnicodeString(string s)
{
    StringBuilder sb = new StringBuilder();
    foreach (char c in s)
    {
        sb.Append("\\u");
        sb.Append(String.Format("{0:x4}", (int)c));
    }
    return sb.ToString();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.