开发者

Escaping an unicode string using backslash notation in c#

how i 开发者_如何学编程can convert this word

mamá

to this word

mam\U00E1


You're looking for something like the code below.

StringBuilder sb = new StringBuilder();
string word = "mamá";
foreach (char c in word)
{
    if (' ' <= c && c <= '~')
    {
        sb.Append(c);
    }
    else
    {
        sb.AppendFormat("\\U{0:X4}", (int)c);
    }
}
string escapedWord = sb.ToString();

Or in a more compact way:

Func<char, string> escapeIfNecessary = c => (' ' <= c && c <= '~') ? c.ToString() : string.Format("\\U{0:X4}", (int)c);
escapedWord = string.Join("", word.Select(escapeIfNecessary).ToArray());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜