gpt4 book ai didi

c# - 如何检查无效的 UTF-8 字符?

转载 作者:行者123 更新时间:2023-12-05 00:40:18 26 4
gpt4 key购买 nike

现在有很多受支持的十六进制 (UTF-8) 实体,从十进制值 0 到 10175,有没有一种快速的方法来检查变量中包含的某个值是支持的十六进制 ( UTF-8) 实体。

例如

var something="some string value";
char[] validCharacter = new[] { All 10175 UTF-8 Hexadecimal characters };
if(validCharacter.Contains(something))
{ \\do something };

我怎样才能以最快的方式进行这项检查?

最佳答案

这应该返回您所询问的内容。它将检查是否缺少未配对的高/低代理和未定义的代码点(“定义”取决于您正在使用的 .NET 版本和操作系统版本中存在的 unicode 表)

static bool IsLegalUnicode(string str)
{
for (int i = 0; i < str.Length; i++)
{
var uc = char.GetUnicodeCategory(str, i);

if (uc == UnicodeCategory.Surrogate)
{
// Unpaired surrogate, like "😵"[0] + "A" or "😵"[1] + "A"
return false;
}
else if (uc == UnicodeCategory.OtherNotAssigned)
{
// \uF000 or \U00030000
return false;
}

// Correct high-low surrogate, we must skip the low surrogate
// (it is correct because otherwise it would have been a
// UnicodeCategory.Surrogate)
if (char.IsHighSurrogate(str, i))
{
i++;
}
}

return true;
}

请注意,Unicode 正在不断扩展。 UTF-8 能够映射所有 Unicode 代码点,即使是目前无法分配的代码点。

一些例子:

var test1 = IsLegalUnicode("abcdeàèéìòù"); // true
var test2 = IsLegalUnicode("⭐ White Medium Star"); // true, Unicode 5.1
var test3 = IsLegalUnicode("😁 Beaming Face With Smiling Eyes"); // true, Unicode 6.0
var test4 = IsLegalUnicode("🙂 Slightly Smiling Face"); // true, Unicode 7.0
var test5 = IsLegalUnicode("🤗 Hugging Face"); // true, Unicode 8.0
var test6 = IsLegalUnicode("🤣 Rolling on the Floor Laughing"); // false, Unicode 9.0 (2016)

var test7 = IsLegalUnicode("🤩 Star-Struck"); // false, Unicode 10.0 (2017)

var test8 = IsLegalUnicode("\uFF00"); // false, undefined BMP UTF-16 unicode

var test9 = IsLegalUnicode("😀"[0] + "X"); // false, unpaired high surrogate pair
var test10 = IsLegalUnicode("😀"[1] + "X"); // false, unpaired low surrogate pair

请注意,即使是格式良好的“未知”Unicode 代码点,您也可以使用 UTF-8 进行编码,例如 🤩 Star-Struck

在 Windows 10 下使用 .NET 4.7.2 取得的结果。

关于c# - 如何检查无效的 UTF-8 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50761133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com