如果可以按 unicode 顺序排列它们,您可以:
Encoding enc = (Encoding)Encoding.GetEncoding("iso-2022-jp").Clone();
enc.EncoderFallback = new EncoderReplacementFallback("");
char[] chars = new char[1];
byte[] bytes = new byte[16];
using (StreamWriter sw = new StreamWriter(@"C:\temp\iso-2022-jp.txt"))
{
for (int i = 0; i <= char.MaxValue; i++)
{
chars[0] = (char)i;
int count = enc.GetBytes(chars, 0, 1, bytes, 0);
if (count != 0)
{
sw.WriteLine(chars[0]);
}
}
}
如果你想按字节顺序排序,你可以:
Encoding enc = (Encoding)Encoding.GetEncoding("iso-2022-jp").Clone();
enc.EncoderFallback = new EncoderReplacementFallback("");
char[] chars = new char[1];
byte[] bytes = new byte[16];
var lst = new List<Tuple<byte[], char>>();
for (int i = 0; i <= char.MaxValue; i++)
{
chars[0] = (char)i;
int count = enc.GetBytes(chars, 0, 1, bytes, 0);
if (count != 0)
{
var bytes2 = new byte[count];
Array.Copy(bytes, bytes2, count);
lst.Add(Tuple.Create(bytes2, chars[0]));
}
}
lst.Sort((x, y) =>
{
int min = Math.Min(x.Item1.Length, y.Item1.Length);
for (int i = 0; i < min; i++)
{
int cmp = x.Item1[i].CompareTo(y.Item1[i]);
if (cmp != 0)
{
return cmp;
}
}
return x.Item1.Length.CompareTo(y.Item1.Length);
});
using (StreamWriter sw = new StreamWriter(@"C:\temp\iso-2022-jp.txt"))
{
foreach (var tuple in lst)
{
sw.WriteLine(tuple.Item2);
// This will print the full byte sequence necessary to
// generate the char. Note that iso-2022-jp uses escape
// sequences to "activate" subtables and to deactivate them.
//sw.WriteLine("{0}: {1}", tuple.Item2, string.Join(",", tuple.Item1.Select(x => x.ToString("x2"))));
}
}
或使用不同的排序顺序(长度优先):
lst.Sort((x, y) =>
{
int cmp2 = x.Item1.Length.CompareTo(y.Item1.Length);
if (cmp2 != 0)
{
return cmp2;
}
int min = Math.Min(x.Item1.Length, y.Item1.Length);
for (int i = 0; i < min; i++)
{
int cmp = x.Item1[i].CompareTo(y.Item1[i]);
if (cmp != 0)
{
return cmp;
}
}
return 0;
});
请注意,在所有示例中,我只生成基本 BMP 平面的字符。我不认为基本 BMP 平面之外的字符包含在任何编码中……如有必要,我可以修改代码以支持它。
出于好奇,第一个版本的代码处理了非 BMP 字符(iso-2022-jp 中不存在):
Encoding enc = (Encoding)Encoding.GetEncoding("iso-2022-jp").Clone();
enc.EncoderFallback = new EncoderReplacementFallback("");
byte[] bytes = new byte[16];
using (StreamWriter sw = new StreamWriter(@"C:\temp\iso-2022-jp.txt"))
{
int max = -1;
for (int i = 0; i <= 0x10FFFF; i++)
{
if (i >= 0xD800 && i <= 0xDFFF)
{
continue;
}
string chars = char.ConvertFromUtf32(i);
int count = enc.GetBytes(chars, 0, chars.Length, bytes, 0);
if (count != 0)
{
sw.WriteLine(chars);
max = i;
}
}
Console.WriteLine("maximum codepoint: {0}", max);
}