从其代码中获取 unicode 字符串 - C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/994459/
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
Getting unicode string from its code - C#
提问by Navaneeth K N
I know following is the way to use unicode in C#
我知道以下是在 C# 中使用 unicode 的方法
string unicodeString = "\u0D15";
In my situation, I will not get the character code (0D15) at compile time. I get this from a XML file at runtime. I wonder how do I convert this code to unicode string? I tried the following
在我的情况下,我不会在编译时获得字符代码(0D15)。我在运行时从一个 XML 文件中得到这个。我想知道如何将此代码转换为 unicode 字符串?我尝试了以下
// will not compile as unrecognized escape sequence
string unicodeString = "\u" + codeFromXML;
// will compile, but just concatenates u with the string got from XML file.
string unicodeString = "\u" + codeFromXML;
How do I handle this situation?
我该如何处理这种情况?
Any help would be great!
任何帮助都会很棒!
采纳答案by arul
You want to use the char.ConvertFromUtf32function.
您想使用char.ConvertFromUtf32函数。
string codePoint = "0D15";
int code = int.Parse(codePoint, System.Globalization.NumberStyles.HexNumber);
string unicodeString = char.ConvertFromUtf32(code);
// unicodeString = "?"
回答by dplante
Here's an NUnit test showing arul and Adrian's solution - note that one solution starts with input in a string, while with the other solution the input starts in just a char.
这是一个 NUnit 测试,显示了 arul 和 Adrian 的解决方案 - 请注意,一个解决方案以字符串中的输入开始,而对于另一个解决方案,输入仅以字符开头。
[Test]
public void testConvertFromUnicode()
{
char myValue = Char.Parse("\u0D15");
Assert.AreEqual(3349, myValue);
char unicodeChar = '\u0D15';
string unicodeString = Char.ConvertFromUtf32(unicodeChar);
Assert.AreEqual(1, unicodeString.Length);
char[] charsInString = unicodeString.ToCharArray();
Assert.AreEqual(1, charsInString.Count());
Assert.AreEqual((int) '\u0D15', charsInString[0]);
}
回答by Jimmy
Escape the character in the xml using a character reference:
<Config value="ക" />
It will get read properly by c#'s xml parser (at least XElement.Load()).
它将被 c# 的 xml 解析器正确读取(至少是 XElement.Load())。