c#

C#如何自定义字符编码表

小樊
85
2024-07-16 17:06:53
栏目: 编程语言

在C#中,可以通过自定义字符编码表来实现字符的自定义映射关系。一种简单的方式是使用字典(Dictionary)来存储字符和对应的编码值。以下是一个示例代码,展示了如何自定义字符编码表:

using System;
using System.Collections.Generic;

class CustomEncoding
{
    private static Dictionary<char, string> encodingTable = new Dictionary<char, string>()
    {
        {'A', "001"},
        {'B', "010"},
        {'C', "011"},
        {'D', "100"},
        // 添加更多的自定义字符和编码值
    };

    public static string EncodeString(string input)
    {
        string encodedString = "";
        foreach (char c in input)
        {
            if (encodingTable.ContainsKey(c))
            {
                encodedString += encodingTable[c];
            }
            else
            {
                encodedString += c;
            }
        }
        return encodedString;
    }

    public static string DecodeString(string encodedInput)
    {
        string decodedString = "";
        string currentChar = "";
        foreach (char c in encodedInput)
        {
            currentChar += c;
            foreach (var entry in encodingTable)
            {
                if (entry.Value == currentChar)
                {
                    decodedString += entry.Key;
                    currentChar = "";
                    break;
                }
            }
        }
        return decodedString;
    }

    static void Main(string[] args)
    {
        string input = "ABCD";
        string encodedString = EncodeString(input);
        Console.WriteLine("Encoded string: " + encodedString);

        string decodedString = DecodeString(encodedString);
        Console.WriteLine("Decoded string: " + decodedString);
    }
}

在以上示例中,我们定义了一个encodingTable字典来存储字符和对应的编码值。EncodeString方法用于将输入字符串编码为自定义编码表中的值,DecodeString方法用于解码编码后的字符串。最后在Main方法中演示了如何使用这个自定义的字符编码表。您可以根据需求修改编码表中的字符和对应的编码值。

0
看了该问题的人还看了