如何从 .NET 字符串中获取 Unicode 代码点数组? [英] How would you get an array of Unicode code points from a .NET String?

查看:23
本文介绍了如何从 .NET 字符串中获取 Unicode 代码点数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符范围限制列表,我需要检查一个字符串,但 .NET 中的 char 类型是 UTF-16,因此某些字符会变成古怪的(代理)对.因此,当枚举 string 中的所有 char 时,我没有得到 32 位 Unicode 代码点,并且一些高值比较失败.

I have a list of character range restrictions that I need to check a string against, but the char type in .NET is UTF-16 and therefore some characters become wacky (surrogate) pairs instead. Thus when enumerating all the char's in a string, I don't get the 32-bit Unicode code points and some comparisons with high values fail.

我对 Unicode 有足够的了解,如有必要,我可以自己解析字节,但我正在寻找 C#/.NET Framework BCL 解决方案.所以...

I understand Unicode well enough that I could parse the bytes myself if necessary, but I'm looking for a C#/.NET Framework BCL solution. So ...

如何将 string 转换为 32 位 Unicode 代码点的数组 (int[])?

How would you convert a string to an array (int[]) of 32-bit Unicode code points?

推荐答案

这个答案不正确.请参阅@Virtlink 的正确答案.

static int[] ExtractScalars(string s)
{
  if (!s.IsNormalized())
  {
    s = s.Normalize();
  }

  List<int> chars = new List<int>((s.Length * 3) / 2);

  var ee = StringInfo.GetTextElementEnumerator(s);

  while (ee.MoveNext())
  {
    string e = ee.GetTextElement();
    chars.Add(char.ConvertToUtf32(e, 0));
  }

  return chars.ToArray();
}

注意事项:处理复合字符需要规范化.

Notes: Normalization is required to deal with composite characters.

这篇关于如何从 .NET 字符串中获取 Unicode 代码点数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆