问题描述
我有一个字符范围限制列表,我需要检查一个字符串,但 .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 代码点数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)