How would you get an array of Unicode code points from a .NET String?(如何从 .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 代码点数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 .NET 字符串中获取 Unicode 代码点数组?


基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01