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 代码点数组?
基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
