Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a string to a sequence of C# Unicode character literals

I'm looking for a way to convert a string into a sequence of Unicode character literals in C#.

For example:

Input:

Hi!

Output:

\u0048\u0069\u0021
like image 481
Ilia Anastassov Avatar asked Dec 18 '22 16:12

Ilia Anastassov


2 Answers

If you mean you want that output as string, you can iterate through all the characters get their Unicode hex values:

const string value = "Hi!";

var chars = value
    .Select(c => (int) c)
    .Select(c => $@"\u{c:x4}");

var result = string.Concat(chars);

See this fiddle for a working demo.

like image 150
Charles Mager Avatar answered Dec 28 '22 22:12

Charles Mager


Here's the same approach, implemented with StringBuilder.

StringBuilder sb = new StringBuilder();
foreach (char c in s)
    sb.AppendFormat("\\u{0:X4}",(uint)c);
return sb.ToString();
like image 25
Sean R Avatar answered Dec 28 '22 22:12

Sean R