C# 如何使用编码删除特定字符。转换

C# 如何使用编码删除特定字符。转换,c#,.net,encoding,utf-8,character-encoding,C#,.net,Encoding,Utf 8,Character Encoding,我正在通过WebClient将签名的XML发送到网关。现在我必须确保节点值只包含德语字母。我有两个测试词。通过使用以下方法,第一个可以很好地转换: string foreignString = "Łůj꣥ü"; Encoding utf8 = Encoding.UTF8; Encoding iso = Encoding.GetEncoding("ISO-8859-1"); byte[] utfBytes = Encoding.Convert(iso, utf8, iso.GetBytes(f

我正在通过WebClient将签名的XML发送到网关。现在我必须确保节点值只包含德语字母。我有两个测试词。通过使用以下方法,第一个可以很好地转换:

string foreignString = "Łůj꣥ü";
Encoding utf8 = Encoding.UTF8;
Encoding iso = Encoding.GetEncoding("ISO-8859-1");
byte[] utfBytes = Encoding.Convert(iso, utf8, iso.GetBytes(foreignString));
string result = utf8.GetString(utfBytes);
但第二个字符串中有一个字符,它也包含在UTF-8编码中。是

ç (Latin small letter c with cedilla)
在使用其他编码进行了一点测试后,我总是得到相同的结果:字符始终存在。有什么意义,因为它是UTF-8表的一部分:)

所以我的问题是:有没有一种方法可以在不删除德语单词的情况下屏蔽所有的法语、葡萄牙语和西班牙语字符


提前谢谢

您可以根据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];
  }

}
结果字符串是
LujeLAüc


请注意,实现非常简单,它使用字典来执行字节的额外映射步骤。这可能不是有效的,但在这种情况下,您可以考虑使用256字节映射数组的替代方案。此外,您还需要展开
charMappingTable
,以包含所有要执行的其他映射。

感谢您提供了出色的解决方案!
var encoding = new GermanEncoding();
string foreignString = "Łůj꣥üç";
var bytes = encoding.GetBytes(foreignString);
var result = encoding.GetString(bytes);