1

这篇文章可能比代码更理论。

我想知道是否有一种(相对)simple方法来使用文本表(基本上是一个字符数组)并根据它们的值替换字符串中的字符。

让我详细说明。

假设我们有这个两行表:

table[0x0] = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'};
table[0x1] = new char[] {'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ']', ',', '/', '.', '~', '&'};

每个数组有 16 个成员,十六进制为 0-F。

假设我们有一个字符串“hello”转换为十六进制(68 65 6C 6C 6F)。我想获取这些十六进制数字,并将它们映射到上表中定义的新位置。

所以,“你好”现在看起来像这样:

07 04 0B 0B 0E

我可以轻松地将字符串转换为数组,但我不知道下一步该做什么。我觉得 foreach 循环可以解决问题,但我还不知道它的确切内容。

是否有捷径可寻?似乎它不应该太难,但我不太确定如何去做。

非常感谢您的帮助!

4

1 回答 1

1
static readonly char[] TABLE = {
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
    'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ']', ',', '/', '.', '~', '&',
};

// Make a lookup dictionary of char => index in the table, for speed.
static readonly Dictionary<char, int> s_lookup = TABLE.ToDictionary(
            c => c,                          // Key is the char itself.
            c => Array.IndexOf(TABLE, c));   // Value is the index of that char.

static void Main(string[] args) {

    // The test input string. Note it has no space.
    string str = "hello,world.";

    // For each character in the string, we lookup what its index in the
    // original table was.
    IEnumerable<int> indices = str.Select(c => s_lookup[c]);

    // Print those numbers out, first converting them to two-digit hex values,
    // and then joining them with commas in-between.
    Console.WriteLine(String.Join(",", indices.Select(i => i.ToString("X02"))));
}

输出:

07,04,0B,0B,0E,1B,16,0E,11,0B,03,1D

请注意,如果您提供的输入字符不在查找表中,您不会立即注意到它! Select返回一个IEnumerable,只有当你去使用它时才会懒惰地评估它。此时,如果未找到输入字符,则字典[]调用将抛出异常。

使这一点更明显的一种方法是ToArray()在 Select 之后调用,因此您有一个索引数组,而不是IEnumerable. 这将迫使评估立即发生:

int[] indices = str.Select(c => s_lookup[c]).ToArray();

参考:

于 2013-01-15T06:46:19.463 回答