C# 中的字符串到 Unicode
我想在我的代码中使用 Unicode 。我的 Unicode 值是 0100,我将我的 Unicode 字符串 \u
添加到我的值中。当我使用字符串 myVal="\u0100"
时,它可以工作,但是当我像下面这样使用时,它不起作用。该值类似于 "\\u1000";
。我该如何解决这个问题?
我想像下面这样使用它,因为 Unicode 值有时可能会有所不同。
string uStr=@"\u" + "0100";
I want to use Unicode in my code. My Unicode value is 0100 and I am adding my Unicode string \u
with my value. When I use string myVal="\u0100"
, it's working, but when I use like below, it's not working. The value is looking like "\\u1000";
. How do I resolve this?
I want to use it like the below one, because the Unicode value may vary sometimes.
string uStr=@"\u" + "0100";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有几个问题。一是@“\u”实际上是文字字符串“\u”(也可以表示为“\u”)。
另一个问题是您无法按照您描述的方式构造字符串,因为“\u”本身不是有效的字符串。编译器期望“\u”后面有一个值(如“\u0100”)来确定编码值应该是什么。
您需要记住 .NET 中的字符串是不可变的,这意味着当您使用串联示例(`@"\u"+"0100")查看幕后发生的情况,这就是实际发生的情况:
所以内存中有三个字符串。为了实现这一点,所有字符串都必须有效。
处理这些值时想到的第一个选项是将它们实际解析为整数,然后将它们转换为字符。类似于:
这将为您提供单个 Unicode 字符值。从那里,您可以将其添加到字符串,或使用
ToString()
将其转换为字符串。There are a couple of problems here. One is that @"\u" is actually the literal string "\u" (can also be represented as "\u").
The other issue is that you cannot construct a string in the way you describe because "\u" is not a valid string by itself. The compiler is expecting a value to follow "\u" (like "\u0100") to determine what the encoded value is supposed to be.
You need to keep in mind that strings in .NET are immutable, which means that when you look at what is going on behind the scenes with your concatenated example (`@"\u"+"0100"), this is what is actually happening:
So you have three strings in memory. In order for that to happen all of the strings must be valid.
The first option that comes to mind for handling those values is to actually parse them as integers, and then convert them to characters. Something like:
Which will give you the single Unicode character value. From there, you can add it to a string, or convert it to a string using
ToString()
.