在 C# 中,将字符转换为 Unicode 编码(即字符的 Unicode 码点)非常简单。每个字符在 C# 中都是一个 char
类型,而 char
类型本质上是一个 16 位的 Unicode 字符。你可以通过以下方法将字符转换为 Unicode 编码:
1. 使用隐式转换
char
类型可以直接隐式转换为 int
类型,获取其 Unicode 码点。
示例代码:
using System;
class Program
{
static void Main()
{
char character = 'A'; // 字符
int unicodeValue = character; // 隐式转换为 Unicode 码点
Console.WriteLine($"字符: {character}, Unicode 值: {unicodeValue}");
// 输出: 字符: A, Unicode 值: 65
}
}
2. 使用 Convert.ToInt32
你也可以使用 Convert.ToInt32
方法将 char
转换为 int
,获取其 Unicode 码点。
示例代码:
using System;
class Program
{
static void Main()
{
char character = '你'; // 中文字符
int unicodeValue = Convert.ToInt32(character); // 转换为 Unicode 码点
Console.WriteLine($"字符: {character}, Unicode 值: {unicodeValue}");
// 输出: 字符: 你, Unicode 值: 20320
}
}
3. 将字符串中的每个字符转换为 Unicode 编码
如果需要将字符串中的每个字符转换为 Unicode 编码,可以遍历字符串并获取每个字符的 Unicode 值。
示例代码:
using System;
class Program
{
static void Main()
{
string input = "Hello 你好";
foreach (char c in input)
{
int unicodeValue = c; // 获取字符的 Unicode 值
Console.WriteLine($"字符: {c}, Unicode 值: {unicodeValue}");
}
}
}
输出:
字符: H, Unicode 值: 72
字符: e, Unicode 值: 101
字符: l, Unicode 值: 108
字符: l, Unicode 值: 108
字符: o, Unicode 值: 111
字符: , Unicode 值: 32
字符: 你, Unicode 值: 20320
字符: 好, Unicode 值: 22909
4. 处理代理对(Surrogate Pair)
对于某些 Unicode 字符(如表情符号),它们可能由两个 char
值(称为代理对)表示。可以使用 char.IsSurrogatePair
和 char.ConvertToUtf32
来处理。
示例代码:
using System;
class Program
{
static void Main()
{
string input = "😊"; // 表情符号
for (int i = 0; i < input.Length; i++)
{
if (char.IsSurrogatePair(input, i))
{
// 处理代理对
int codePoint = char.ConvertToUtf32(input, i);
Console.WriteLine($"字符: {input.Substring(i, 2)}, Unicode 值: {codePoint}");
i++; // 跳过下一个 char
}
else
{
// 处理普通字符
int unicodeValue = input[i];
Console.WriteLine($"字符: {input[i]}, Unicode 值: {unicodeValue}");
}
}
}
}
输出:
字符: 😊, Unicode 值: 128522
5. 将 Unicode 值格式化为 \uHHHH
或 \UHHHHHHHH
如果需要将 Unicode 值格式化为 \uHHHH
(4 位十六进制)或 \UHHHHHHHH
(8 位十六进制),可以使用 ToString("X4")
或 ToString("X8")
。
示例代码:
using System;
class Program
{
static void Main()
{
char character = 'A'; // 字符
int unicodeValue = character; // 获取 Unicode 值
string unicodeEscape = $"\\u{unicodeValue:X4}"; // 格式化为 \uHHHH
Console.WriteLine($"字符: {character}, Unicode 转义字符: {unicodeEscape}");
// 输出: 字符: A, Unicode 转义字符: \u0041
string emoji = "😊"; // 表情符号
int emojiCodePoint = char.ConvertToUtf32(emoji, 0); // 获取 Unicode 码点
string emojiEscape = $"\\U{emojiCodePoint:X8}"; // 格式化为 \UHHHHHHHH
Console.WriteLine($"字符: {emoji}, Unicode 转义字符: {emojiEscape}");
// 输出: 字符: 😊, Unicode 转义字符: \U0001F60A
}
}
6. 总结
- 使用隐式转换或
Convert.ToInt32
将字符转换为 Unicode 码点。 - 遍历字符串可以获取每个字符的 Unicode 值。
- 对于代理对字符,使用
char.ConvertToUtf32
获取完整的 Unicode 码点。 - 使用
ToString("X4")
或ToString("X8")
将 Unicode 值格式化为\uHHHH
或\UHHHHHHHH
。
通过这些方法,你可以在 C# 中轻松地将字符转换为 Unicode 编码。