C# 将字符串转换为 Unicode 表示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13291339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:05:47  来源:igfitidea点击:

Convert string to unicode representation

c#.netstring

提问by Royi Namir

Possible Duplicate:
Converting Unicode strings to escaped ascii string

可能的重复:
将 Unicode 字符串转换为转义的 ascii 字符串

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

我怎样才能转换?...成类似的东西 \u0131...

is there any Function for doing this ?

有没有这样做的功能?

p.s :

附:

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

除此之外:[抱歉@Kendall Frey :-)]

char a = '?';
string escape = "\u" + ((int)a).ToString("X").PadLeft(4, '0');

采纳答案by Kendall Frey

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.

不,据我所知,没有内置功能。

回答by ChruS

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

AFAIK 没有内置函数。这是一个非常愚蠢的解决方案。但是 Kendall Frey 提供了更好的变体。

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