.NET String 对象是否可能包含无效的 Unicode 代码点?
如果是,这怎么会发生(以及我如何确定字符串是否具有这样的无效字符)?
最佳答案
虽然@DPenner 给出的回复非常好(我用它作为起点),但我想提供一些其他细节。
除了孤立的代理之外,我认为这是无效字符串的明显标志,字符串总是有可能包含未分配的代码点,并且这种情况不能被 .NET Framework 视为错误,因为新字符总是添加到 Unicode 标准中,例如参见 Unicode http://en.wikipedia.org/wiki/Unicode#Versions 的版本.而且,为了让事情更清楚,这个电话Char.GetUnicodeCategory(Char.ConvertFromUtf32(0x1F01C), 0);
返回 UnicodeCategory.OtherNotAssigned
当使用 .NET 2.0 时,它会返回 UnicodeCategory.OtherSymbol
使用 .NET 4.0 时。
除此之外,还有一个有趣的点:甚至 .NET 类库方法在如何处理 Unicode 非字符和未配对的代理字符方面也没有达成一致。例如:
System.Text.Encoding.Unicode.GetBytes("\uDDDD");
- 返回 { 0xfd, 0xff}
Replacement character 的编码,即认为数据无效。 "\uDDDD".Normalize();
- 引发异常并显示消息“在索引 0 处找到无效的 Unicode 代码点。”,即数据被视为无效。 System.Text.Encoding.Unicode.GetBytes("\uFFFF");
- 返回 {0xff, 0xff}
,也就是说,数据被认为是有效的。 "\uFFFF".Normalize();
- 抛出消息“在索引 0 处发现无效 Unicode 代码点。”的异常,即数据被视为无效。 下面是一个将在字符串中搜索无效字符的方法:
/// <summary>
/// Searches invalid charachters (non-chars defined in Unicode standard and invalid surrogate pairs) in a string
/// </summary>
/// <param name="aString"> the string to search for invalid chars </param>
/// <returns>the index of the first bad char or -1 if no bad char is found</returns>
static int FindInvalidCharIndex(string aString)
{
int ch;
int chlow;
for (int i = 0; i < aString.Length; i++)
{
ch = aString[i];
if (ch < 0xD800) // char is up to first high surrogate
{
continue;
}
if (ch >= 0xD800 && ch <= 0xDBFF)
{
// found high surrogate -> check surrogate pair
i++;
if (i == aString.Length)
{
// last char is high surrogate, so it is missing its pair
return i - 1;
}
chlow = aString[i];
if (!(chlow >= 0xDC00 && chlow <= 0xDFFF))
{
// did not found a low surrogate after the high surrogate
return i - 1;
}
// convert to UTF32 - like in Char.ConvertToUtf32(highSurrogate, lowSurrogate)
ch = (ch - 0xD800) * 0x400 + (chlow - 0xDC00) + 0x10000;
if (ch > 0x10FFFF)
{
// invalid Unicode code point - maximum excedeed
return i;
}
if ((ch & 0xFFFE) == 0xFFFE)
{
// other non-char found
return i;
}
// found a good surrogate pair
continue;
}
if (ch >= 0xDC00 && ch <= 0xDFFF)
{
// unexpected low surrogate
return i;
}
if (ch >= 0xFDD0 && ch <= 0xFDEF)
{
// non-chars are considered invalid by System.Text.Encoding.GetBytes() and String.Normalize()
return i;
}
if ((ch & 0xFFFE) == 0xFFFE)
{
// other non-char found
return i;
}
}
return -1;
}
关于.NET String 对象和无效的 Unicode 代码点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27049478/