Encoding
您可以使用附加的特殊规则基于 ISO-8859-1 编码创建自己的类:
class GermanEncoding : Encoding {
static readonly Encoding iso88791Encoding = Encoding.GetEncoding("ISO-8859-1");
static readonly Dictionary<Char, Char> charMappingTable = new Dictionary<Char, Char> {
{ 'À', 'A' },
{ 'Á', 'A' },
{ 'Â', 'A' },
{ 'ç', 'c' },
// Add more mappings
};
static readonly Dictionary<Byte, Byte> byteMappingTable = charMappingTable
.ToDictionary(kvp => MapCharToByte(kvp.Key), kvp => MapCharToByte(kvp.Value));
public override Int32 GetByteCount(Char[] chars, Int32 index, Int32 count) {
return iso88791Encoding.GetByteCount(chars, index, count);
}
public override Int32 GetBytes(Char[] chars, Int32 charIndex, Int32 charCount, Byte[] bytes, Int32 byteIndex) {
var count = iso88791Encoding.GetBytes(chars, charIndex, charCount, bytes, byteIndex);
for (var i = byteIndex; i < byteIndex + count; ++i)
if (byteMappingTable.ContainsKey(bytes[i]))
bytes[i] = byteMappingTable[bytes[i]];
return count;
}
public override Int32 GetCharCount(Byte[] bytes, Int32 index, Int32 count) {
return iso88791Encoding.GetCharCount(bytes, index, count);
}
public override Int32 GetChars(Byte[] bytes, Int32 byteIndex, Int32 byteCount, Char[] chars, Int32 charIndex) {
return iso88791Encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
}
public override Int32 GetMaxByteCount(Int32 charCount) {
return iso88791Encoding.GetMaxByteCount(charCount);
}
public override Int32 GetMaxCharCount(Int32 byteCount) {
return iso88791Encoding.GetMaxCharCount(byteCount);
}
static Byte MapCharToByte(Char c) {
// NOTE: Assumes that each character encodes as a single byte.
return iso88791Encoding.GetBytes(new[] { c })[0];
}
}
此编码基于您希望使用 ISO-8859-1 编码以及一些附加限制的事实,您希望将“非德语”字符映射到其 ASCII 等效字符。内置的 ISO-8859-1 编码知道如何映射Ł
到L
,因为 ISO-8859-1 是单字节字符集,您可以对字节进行额外的映射,因为每个字节对应一个字符。这是在GetBytes
方法中完成的。
您可以使用以下代码“清理”字符串:
var encoding = new GermanEncoding();
string foreignString = "Łůj꣥üç";
var bytes = encoding.GetBytes(foreignString);
var result = encoding.GetString(bytes);
结果字符串是LujeLAüc
.
请注意,该实现非常简单,它使用字典来执行字节的附加映射步骤。这可能效率不高,但在这种情况下,您可以考虑使用 256 字节映射数组等替代方法。此外,您需要扩展charMappingTable
以包含您要执行的所有其他映射。