开发者

Escaping an unicode string using backslash notation in c#

开发者 https://www.devze.com 2023-03-13 10:24 出处:网络
how i 开发者_如何学编程can convert this word mamá to this word mam\\U00E1 You\'re looking for something like the code below.

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

精彩评论

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